Initial commit: apps.supersam24.ru
This commit is contained in:
commit
e955e1da36
6566 files changed
+1271095
No files matched your search
Vendored
+24
@@ -0,0 +1,24 @@
|
||||
# Basic docker based environment
|
||||
# Necessary to trick dokku into building the documentation
|
||||
# using dockerfile instead of herokuish
|
||||
FROM ubuntu:17.04
|
||||
|
||||
# Add basic tools
|
||||
RUN apt-get update && \
|
||||
apt-get install -y build-essential \
|
||||
software-properties-common \
|
||||
curl \
|
||||
git \
|
||||
libxml2 \
|
||||
libffi-dev \
|
||||
libssl-dev
|
||||
|
||||
RUN LC_ALL=C.UTF-8 add-apt-repository ppa:ondrej/php && \
|
||||
apt-get update && \
|
||||
apt-get install -y php7.2-cli php7.2-mbstring php7.2-xml php7.2-zip php7.2-intl php7.2-opcache php7.2-sqlite
|
||||
|
||||
WORKDIR /code
|
||||
|
||||
VOLUME ["/code"]
|
||||
|
||||
CMD [ '/bin/bash' ]
|
||||
Vendored
+28
@@ -0,0 +1,28 @@
|
||||
The MIT License
|
||||
|
||||
CakePHP(tm) : The Rapid Development PHP Framework (http://cakephp.org)
|
||||
Copyright (c) 2005-present, Cake Software Foundation, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of this software and associated documentation files (the "Software"),
|
||||
to deal in the Software without restriction, including without limitation
|
||||
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
and/or sell copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
|
||||
Cake Software Foundation, Inc.
|
||||
1785 E. Sahara Avenue,
|
||||
Suite 490-204
|
||||
Las Vegas, Nevada 89104,
|
||||
United States of America.
|
||||
Vendored
+38
@@ -0,0 +1,38 @@
|
||||
# Bake plugin for CakePHP
|
||||
|
||||
[](https://travis-ci.org/cakephp/bake)
|
||||
[](https://codecov.io/github/cakephp/bake)
|
||||
[](LICENSE.txt)
|
||||
|
||||
This project provides the code generation functionality for CakePHP. Through a
|
||||
suite of CLI tools, you can quickly and easily generate code for your application.
|
||||
|
||||
## Installation
|
||||
|
||||
You can install this plugin into your CakePHP application using [composer](http://getcomposer.org).
|
||||
|
||||
The recommended way to install composer packages is:
|
||||
|
||||
```
|
||||
composer require --dev cakephp/bake
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
You can find the documentation for bake [on its own cookbook](https://book.cakephp.org/bake/1.x/en/index.html).
|
||||
|
||||
## Testing
|
||||
|
||||
After installing dependencies with composer you can run tests with `phpunit`:
|
||||
|
||||
```bash
|
||||
vendor/bin/phpunit
|
||||
```
|
||||
|
||||
If your changes require changing the templates that bake uses, you can save time updating tests, by
|
||||
enabling bake's 'overwrite fixture feature'. This will let you re-generate the expected output files
|
||||
without having to manually edit each one:
|
||||
|
||||
```bash
|
||||
UPDATE_TEST_COMPARISON_FILES=1 vendor/bin/phpunit
|
||||
```
|
||||
Vendored
+56
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"name": "cakephp/bake",
|
||||
"description": "Bake plugin for CakePHP 3",
|
||||
"type": "cakephp-plugin",
|
||||
"keywords": ["cakephp", "bake"],
|
||||
"homepage": "https://github.com/cakephp/bake",
|
||||
"license": "MIT",
|
||||
"authors": [
|
||||
{
|
||||
"name": "CakePHP Community",
|
||||
"homepage": "https://github.com/cakephp/bake/graphs/contributors"
|
||||
}
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/cakephp/bake/issues",
|
||||
"forum": "https://stackoverflow.com/tags/cakephp",
|
||||
"irc": "irc://irc.freenode.org/cakephp",
|
||||
"source": "https://github.com/cakephp/bake"
|
||||
},
|
||||
"require": {
|
||||
"php": ">=5.6.0",
|
||||
"cakephp/cakephp": "^3.8.0",
|
||||
"cakephp/plugin-installer": "^1.0",
|
||||
"wyrihaximus/twig-view": "^4.3.7"
|
||||
},
|
||||
"require-dev": {
|
||||
"cakephp/cakephp-codesniffer": "^3.0",
|
||||
"phpunit/phpunit": "^5.7.14|^6.0"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Bake\\": "src/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"BakeTest\\": "tests/test_app/Plugin/BakeTest/src/",
|
||||
"Pastry\\PastryTest\\": "tests/test_app/Plugin/PastryTest/src/",
|
||||
"Bake\\Test\\": "tests/",
|
||||
"Bake\\Test\\App\\": "tests/test_app/App/",
|
||||
"Cake\\Test\\": "./vendor/cakephp/cakephp/tests/"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"check": [
|
||||
"@test",
|
||||
"@cs-check"
|
||||
],
|
||||
"cs-check": "phpcs --parallel=16 -p src/ tests/",
|
||||
"cs-fix": "phpcbf --parallel=16 -p src/ tests/",
|
||||
"phpstan": "phpstan analyse src/",
|
||||
"phpstan-setup": "cp composer.json composer.backup && composer require --dev phpstan/phpstan-shim:^0.11 && mv composer.backup composer.json",
|
||||
"test": "phpunit",
|
||||
"test-coverage": "phpunit --coverage-clover=clover.xml"
|
||||
}
|
||||
}
|
||||
Vendored
+18
@@ -0,0 +1,18 @@
|
||||
# Generate the HTML output.
|
||||
FROM markstory/cakephp-docs-builder as builder
|
||||
|
||||
# Copy entire repo in with .git so we can build all versions in one image.
|
||||
COPY docs /data/src
|
||||
|
||||
RUN cd /data/docs-builder \
|
||||
&& make website LANGS="en es fr ja pt ru" SOURCE=/data/src DEST=/data/website/
|
||||
|
||||
# Build a small nginx container with just the static site in it.
|
||||
FROM nginx:1.15-alpine
|
||||
|
||||
COPY --from=builder /data/website /data/website
|
||||
COPY --from=builder /data/docs-builder/nginx.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
# Copy docs into place.
|
||||
RUN cp -R /data/website/html/* /usr/share/nginx/html \
|
||||
&& rm -rf /data/website
|
||||
Whitespace-only changes.
+49
@@ -0,0 +1,49 @@
|
||||
# Global configuration information used across all the
|
||||
# translations of documentation.
|
||||
#
|
||||
# Import the base theme configuration
|
||||
from cakephpsphinx.config.all import *
|
||||
|
||||
# The version info for the project you're documenting, acts as replacement for
|
||||
# |version| and |release|, also used in various other places throughout the
|
||||
# built documents.
|
||||
#
|
||||
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = '1.x'
|
||||
|
||||
# The search index version.
|
||||
search_version = 'bake-1'
|
||||
|
||||
# The marketing display name for the book.
|
||||
version_name = ''
|
||||
|
||||
# Project name shown in the black header bar
|
||||
project = 'CakePHP Bake'
|
||||
|
||||
# Other versions that display in the version picker menu.
|
||||
version_list = [
|
||||
{'name': '1.x', 'number': '/bake/1.x', 'title': '1.x', 'current': True},
|
||||
# {'name': '2.x', 'number': '/bake/2.x', 'title': '2.x'},
|
||||
]
|
||||
|
||||
# Languages available.
|
||||
languages = ['en', 'es', 'fr', 'ja', 'pt', 'ru']
|
||||
|
||||
# The GitHub branch name for this version of the docs
|
||||
# for edit links to point at.
|
||||
branch = 'master'
|
||||
|
||||
# Current version being built
|
||||
version = '1.x'
|
||||
|
||||
# Language in use for this directory.
|
||||
language = 'en'
|
||||
|
||||
show_root_link = True
|
||||
|
||||
repository = 'cakephp/bake'
|
||||
|
||||
source_path = 'docs/'
|
||||
|
||||
hide_page_contents = ('search', '404', 'contents')
|
||||
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
import sys, os
|
||||
|
||||
# Append the top level directory of the docs, so we can import from the config dir.
|
||||
sys.path.insert(0, os.path.abspath('..'))
|
||||
|
||||
# Pull in all the configuration options defined in the global config file..
|
||||
from config.all import *
|
||||
|
||||
language = 'en'
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
:caption: CakePHP Bake
|
||||
|
||||
/index
|
||||
/usage
|
||||
/development
|
||||
+304
@@ -0,0 +1,304 @@
|
||||
Extending Bake
|
||||
##############
|
||||
|
||||
Bake features an extensible architecture that allows your application or plugins
|
||||
to modify or add-to the base functionality. Bake makes use of a dedicated
|
||||
view class which uses the `Twig <https://twig.symfony.com/>`_ template engine.
|
||||
|
||||
Bake Events
|
||||
===========
|
||||
|
||||
As a view class, ``BakeView`` emits the same events as any other view class,
|
||||
plus one extra initialize event. However, whereas standard view classes use the
|
||||
event prefix "View.", ``BakeView`` uses the event prefix "Bake.".
|
||||
|
||||
The initialize event can be used to make changes which apply to all baked
|
||||
output, for example to add another helper to the bake view class this event can
|
||||
be used::
|
||||
|
||||
<?php
|
||||
// config/bootstrap_cli.php
|
||||
|
||||
use Cake\Event\Event;
|
||||
use Cake\Event\EventManager;
|
||||
|
||||
EventManager::instance()->on('Bake.initialize', function (Event $event) {
|
||||
$view = $event->getSubject();
|
||||
|
||||
// In my bake templates, allow the use of the MySpecial helper
|
||||
$view->loadHelper('MySpecial', ['some' => 'config']);
|
||||
|
||||
// And add an $author variable so it's always available
|
||||
$view->set('author', 'Andy');
|
||||
|
||||
});
|
||||
|
||||
If you want to modify bake from within another plugin, putting your plugin's
|
||||
bake events in the plugin ``config/bootstrap.php`` file is a good idea.
|
||||
|
||||
Bake events can be handy for making small changes to existing templates.
|
||||
For example, to change the variable names used when baking controller/template
|
||||
files one can use a function listening for ``Bake.beforeRender`` to modify the
|
||||
variables used in the bake templates::
|
||||
|
||||
<?php
|
||||
// config/bootstrap_cli.php
|
||||
|
||||
use Cake\Event\Event;
|
||||
use Cake\Event\EventManager;
|
||||
|
||||
EventManager::instance()->on('Bake.beforeRender', function (Event $event) {
|
||||
$view = $event->getSubject();
|
||||
|
||||
// Use $rows for the main data variable in indexes
|
||||
if ($view->get('pluralName')) {
|
||||
$view->set('pluralName', 'rows');
|
||||
}
|
||||
if ($view->get('pluralVar')) {
|
||||
$view->set('pluralVar', 'rows');
|
||||
}
|
||||
|
||||
// Use $theOne for the main data variable in view/edit
|
||||
if ($view->get('singularName')) {
|
||||
$view->set('singularName', 'theOne');
|
||||
}
|
||||
if ($view->get('singularVar')) {
|
||||
$view->set('singularVar', 'theOne');
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
You may also scope the ``Bake.beforeRender`` and ``Bake.afterRender`` events to
|
||||
a specific generated file. For instance, if you want to add specific actions to
|
||||
your UsersController when generating from a **Controller/controller.twig** file,
|
||||
you can use the following event::
|
||||
|
||||
<?php
|
||||
// config/bootstrap_cli.php
|
||||
|
||||
use Cake\Event\Event;
|
||||
use Cake\Event\EventManager;
|
||||
use Cake\Utility\Hash;
|
||||
|
||||
EventManager::instance()->on(
|
||||
'Bake.beforeRender.Controller.controller',
|
||||
function (Event $event) {
|
||||
$view = $event->getSubject();
|
||||
if ($view->viewVars['name'] == 'Users') {
|
||||
// add the login and logout actions to the Users controller
|
||||
$view->set('actions', [
|
||||
'login',
|
||||
'logout',
|
||||
'index',
|
||||
'view',
|
||||
'add',
|
||||
'edit',
|
||||
'delete'
|
||||
]);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
By scoping event listeners to specific bake templates, you can simplify your
|
||||
bake related event logic and provide callbacks that are easier to test.
|
||||
|
||||
Bake Template Syntax
|
||||
====================
|
||||
|
||||
Bake template files use the `Twig <https://twig.symfony.com/doc/2.x/>`__ template syntax.
|
||||
|
||||
One way to see/understand how bake templates works, especially when attempting
|
||||
to modify bake template files, is to bake a class and compare the template used
|
||||
with the pre-processed template file which is left in the application's
|
||||
**tmp/bake** folder.
|
||||
|
||||
So, for example, when baking a shell like so:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
bin/cake bake shell Foo
|
||||
|
||||
The template used (**vendor/cakephp/bake/src/Template/Bake/Shell/shell.twig**)
|
||||
looks like this::
|
||||
|
||||
<?php
|
||||
namespace {{ namespace }}\Shell;
|
||||
|
||||
use Cake\Console\Shell;
|
||||
|
||||
/**
|
||||
* {{ name }} shell command.
|
||||
*/
|
||||
class {{ name }}Shell extends Shell
|
||||
{
|
||||
/**
|
||||
* main() method.
|
||||
*
|
||||
* @return bool|int Success or error code.
|
||||
*/
|
||||
public function main()
|
||||
{
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
And the resultant baked class (**src/Shell/FooShell.php**) looks like this::
|
||||
|
||||
<?php
|
||||
namespace App\Shell;
|
||||
|
||||
use Cake\Console\Shell;
|
||||
|
||||
/**
|
||||
* Foo shell command.
|
||||
*/
|
||||
class FooShell extends Shell
|
||||
{
|
||||
/**
|
||||
* main() method.
|
||||
*
|
||||
* @return bool|int Success or error code.
|
||||
*/
|
||||
public function main()
|
||||
{
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
.. note::
|
||||
|
||||
Prior to version 1.5.0 bake used a custom erb-style tags inside .ctp template files.
|
||||
|
||||
* ``<%`` A Bake template php open tag
|
||||
* ``%>`` A Bake template php close tag
|
||||
* ``<%=`` A Bake template php short-echo tag
|
||||
* ``<%-`` A Bake template php open tag, stripping any leading whitespace
|
||||
before the tag
|
||||
* ``-%>`` A Bake template php close tag, stripping trailing whitespace after
|
||||
the tag
|
||||
|
||||
.. _creating-a-bake-theme:
|
||||
|
||||
Creating a Bake Theme
|
||||
=====================
|
||||
|
||||
If you wish to modify the output produced by the "bake" command, you can
|
||||
create your own bake 'theme' which allows you to replace some or all of the
|
||||
templates that bake uses. The best way to do this is:
|
||||
|
||||
#. Bake a new plugin. The name of the plugin is the bake 'theme' name
|
||||
#. Create a new directory **plugins/[name]/src/Template/Bake/Template/**.
|
||||
#. Copy any templates you want to override from
|
||||
**vendor/cakephp/bake/src/Template/Bake/Template** to matching files in your
|
||||
plugin.
|
||||
#. When running bake use the ``--theme`` option to specify the bake-theme you
|
||||
want to use. To avoid having to specify this option in each call, you can also
|
||||
set your custom theme to be used as default theme::
|
||||
|
||||
<?php
|
||||
// in config/bootstrap.php or config/bootstrap_cli.php
|
||||
Configure::write('Bake.theme', 'MyTheme');
|
||||
|
||||
Customizing the Bake Templates
|
||||
==============================
|
||||
|
||||
If you wish to modify the default output produced by the "bake" command, you can
|
||||
create your own bake templates in your application. This way does not use the
|
||||
``--theme`` option in the command line when baking. The best way to do this is:
|
||||
|
||||
#. Create a new directory **/src/Template/Bake/**.
|
||||
#. Copy any templates you want to override from
|
||||
**vendor/cakephp/bake/src/Template/Bake/** to matching files in your
|
||||
application.
|
||||
|
||||
Creating New Bake Command Options
|
||||
=================================
|
||||
|
||||
It's possible to add new bake command options, or override the ones provided by
|
||||
CakePHP by creating tasks in your application or plugins. By extending
|
||||
``Bake\Shell\Task\BakeTask``, bake will find your new task and include it as
|
||||
part of bake.
|
||||
|
||||
As an example, we'll make a task that creates an arbitrary foo class. First,
|
||||
create the task file **src/Shell/Task/FooTask.php**. We'll extend the
|
||||
``SimpleBakeTask`` for now as our shell task will be simple. ``SimpleBakeTask``
|
||||
is abstract and requires us to define 3 methods that tell bake what the task is
|
||||
called, where the files it generates should go, and what template to use. Our
|
||||
FooTask.php file should look like::
|
||||
|
||||
<?php
|
||||
namespace App\Shell\Task;
|
||||
|
||||
use Bake\Shell\Task\SimpleBakeTask;
|
||||
|
||||
class FooTask extends SimpleBakeTask
|
||||
{
|
||||
public $pathFragment = 'Foo/';
|
||||
|
||||
public function name()
|
||||
{
|
||||
return 'foo';
|
||||
}
|
||||
|
||||
public function fileName($name)
|
||||
{
|
||||
return $name . 'Foo.php';
|
||||
}
|
||||
|
||||
public function template()
|
||||
{
|
||||
return 'foo';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Once this file has been created, we need to create a template that bake can use
|
||||
when generating code. Create **src/Template/Bake/foo.twig**. In this file we'll
|
||||
add the following content::
|
||||
|
||||
<?php
|
||||
namespace {{ namespace }}\Foo;
|
||||
|
||||
/**
|
||||
* {{ name }} foo
|
||||
*/
|
||||
class {{ name }}Foo
|
||||
{
|
||||
// Add code.
|
||||
}
|
||||
|
||||
You should now see your new task in the output of ``bin/cake bake``. You can
|
||||
run your new task by running ``bin/cake bake foo Example``.
|
||||
This will generate a new ``ExampleFoo`` class in **src/Foo/ExampleFoo.php**
|
||||
for your application to use.
|
||||
|
||||
If you want the ``bake`` call to also create a test file for your
|
||||
``ExampleFoo`` class, you need to overwrite the ``bakeTest()`` method in the
|
||||
``FooTask`` class to register the class suffix and namespace for your custom
|
||||
command name::
|
||||
|
||||
public function bakeTest($className)
|
||||
{
|
||||
if (!isset($this->Test->classSuffixes[$this->name()])) {
|
||||
$this->Test->classSuffixes[$this->name()] = 'Foo';
|
||||
}
|
||||
|
||||
$name = ucfirst($this->name());
|
||||
if (!isset($this->Test->classTypes[$name])) {
|
||||
$this->Test->classTypes[$name] = 'Foo';
|
||||
}
|
||||
|
||||
return parent::bakeTest($className);
|
||||
}
|
||||
|
||||
* The **class suffix** will be appened to the name provided in your ``bake``
|
||||
call. In the previous example, it would create a ``ExampleFooTest.php`` file.
|
||||
* The **class type** will be the sub-namespace used that will lead to your
|
||||
file (relative to the app or the plugin you are baking into). In the previous
|
||||
example, it would create your test with the namespace ``App\Test\TestCase\Foo``
|
||||
.
|
||||
|
||||
.. meta::
|
||||
:title lang=en: Extending Bake
|
||||
:keywords lang=en: command line interface,development,bake view, bake template syntax,twig,erb tags,percent tags
|
||||
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
Bake Console
|
||||
############
|
||||
|
||||
CakePHP's bake console is another effort to get you up and running in CakePHP
|
||||
– fast. The bake console can create any of CakePHP's basic ingredients: models,
|
||||
behaviors, views, helpers, controllers, components, test cases, fixtures and plugins.
|
||||
And we aren't just talking skeleton classes: Bake can create a fully functional
|
||||
application in just a few minutes. In fact, Bake is a natural step to take once
|
||||
an application has been scaffolded.
|
||||
|
||||
Installation
|
||||
============
|
||||
|
||||
Before trying to use or extend bake, make sure it is installed in your
|
||||
application. Bake is provided as a plugin that you can install with Composer::
|
||||
|
||||
composer require --dev cakephp/bake:~1.0
|
||||
|
||||
The above will install bake as a development dependency. This means that it will
|
||||
not be installed when you do production deployments.
|
||||
|
||||
When using the Twig templates make sure you are loading the
|
||||
``WyriHaximus/TwigView`` plugin with its bootstrap. You can also omit it
|
||||
completely which then makes Bake plugin load this plugin on demand.
|
||||
|
||||
.. meta::
|
||||
:title lang=en: Bake Console
|
||||
:keywords lang=en: command line interface,development,bake view, bake template syntax,erb tags,asp tags,percent tags
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
Code Generation with Bake
|
||||
#########################
|
||||
|
||||
The cake console is run using the PHP CLI (command line interface).
|
||||
If you have problems running the script, ensure that:
|
||||
|
||||
#. You have the PHP CLI installed and that it has the proper modules enabled
|
||||
(eg: MySQL, intl).
|
||||
#. Users also might have issues if the database host is 'localhost' and should
|
||||
try '127.0.0.1' instead, as localhost can cause issues with PHP CLI.
|
||||
#. Depending on how your computer is configured, you may have to set execute
|
||||
rights on the cake bash script to call it using ``bin/cake bake``.
|
||||
|
||||
Before running bake you should make sure you have at least one database
|
||||
connection configured.
|
||||
|
||||
When run with no arguments ``bin/cake bake`` will output a list of available
|
||||
tasks.
|
||||
|
||||
For windows system try with ``bin\cake bake``.
|
||||
|
||||
You should see something like::
|
||||
|
||||
$ bin/cake bake
|
||||
|
||||
Welcome to CakePHP v3.4.6 Console
|
||||
---------------------------------------------------------------
|
||||
App : src
|
||||
Path: /var/www/cakephp.dev/src/
|
||||
PHP : 5.6.20
|
||||
---------------------------------------------------------------
|
||||
The following commands can be used to generate skeleton code for your application.
|
||||
|
||||
Available bake commands:
|
||||
|
||||
- all
|
||||
- behavior
|
||||
- cell
|
||||
- component
|
||||
- controller
|
||||
- fixture
|
||||
- form
|
||||
- helper
|
||||
- mailer
|
||||
- migration
|
||||
- migration_diff
|
||||
- migration_snapshot
|
||||
- model
|
||||
- plugin
|
||||
- seed
|
||||
- shell
|
||||
- shell_helper
|
||||
- task
|
||||
- template
|
||||
- test
|
||||
|
||||
By using `cake bake [name]` you can invoke a specific bake task.
|
||||
|
||||
You can get more information on what each task does, and what options are
|
||||
available using the ``--help`` option::
|
||||
|
||||
$ bin/cake bake --help
|
||||
|
||||
Welcome to CakePHP v3.4.6 Console
|
||||
---------------------------------------------------------------
|
||||
App : src
|
||||
Path: /var/www/cakephp.dev/src/
|
||||
PHP : 5.6.20
|
||||
---------------------------------------------------------------
|
||||
The Bake script generates controllers, models and template files for
|
||||
your application. If run with no command line arguments, Bake guides the
|
||||
user through the class creation process. You can customize the
|
||||
generation process by telling Bake where different parts of your
|
||||
application are using command line arguments.
|
||||
|
||||
Usage:
|
||||
cake bake.bake [subcommand] [options]
|
||||
|
||||
Subcommands:
|
||||
|
||||
all Bake a complete MVC skeleton.
|
||||
behavior Bake a behavior class file.
|
||||
cell Bake a cell class file.
|
||||
component Bake a component class file.
|
||||
controller Bake a controller skeleton.
|
||||
fixture Generate fixtures for use with the test suite. You
|
||||
can use `bake fixture all` to bake all fixtures.
|
||||
form Bake a form class file.
|
||||
helper Bake a helper class file.
|
||||
mailer Bake a mailer class file.
|
||||
migration Bake migration class.
|
||||
migration_diff Bake migration class.
|
||||
migration_snapshot Bake migration snapshot class.
|
||||
model Bake table and entity classes.
|
||||
plugin Create the directory structure, AppController class
|
||||
and testing setup for a new plugin. Can create
|
||||
plugins in any of your bootstrapped plugin paths.
|
||||
seed Bake seed class.
|
||||
shell Bake a shell class file.
|
||||
shell_helper Bake a shell_helper class file.
|
||||
task Bake a task class file.
|
||||
template Bake views for a controller, using built-in or
|
||||
custom templates.
|
||||
test Bake test case skeletons for classes.
|
||||
|
||||
To see help on a subcommand use `cake bake.bake [subcommand] --help`
|
||||
|
||||
Options:
|
||||
|
||||
--connection, -c Database connection to use in conjunction with `bake
|
||||
all`. (default: default)
|
||||
--everything Bake a complete MVC skeleton, using all the available
|
||||
tables. Usage: "bake all --everything"
|
||||
--force, -f Force overwriting existing files without prompting.
|
||||
--help, -h Display this help.
|
||||
--plugin, -p Plugin to bake into.
|
||||
--prefix Prefix to bake controllers and templates into.
|
||||
--quiet, -q Enable quiet output.
|
||||
--tablePrefix Table prefix to be used in models.
|
||||
--theme, -t The theme to use when baking code. (choices:
|
||||
Bake|Migrations)
|
||||
--verbose, -v Enable verbose output.
|
||||
|
||||
Bake Themes
|
||||
===========
|
||||
|
||||
The theme option is common to all bake commands, and allows changing the bake
|
||||
template files used when baking. To create your own templates, see the
|
||||
:ref:`bake theme creation documentation <creating-a-bake-theme>`.
|
||||
|
||||
.. meta::
|
||||
:title lang=en: Code Generation with Bake
|
||||
:keywords lang=en: command line interface,functional application,database,database configuration,bash script,basic ingredients,project,model,path path,code generation,scaffolding,windows users,configuration file,few minutes,config,iew,shell,models,running,mysql
|
||||
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
import sys, os
|
||||
|
||||
# Append the top level directory of the docs, so we can import from the config dir.
|
||||
sys.path.insert(0, os.path.abspath('..'))
|
||||
|
||||
# Pull in all the configuration options defined in the global config file..
|
||||
from config.all import *
|
||||
|
||||
language = 'es'
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
:caption: CakePHP Bake
|
||||
|
||||
/index
|
||||
/usage
|
||||
/development
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
Extending Bake
|
||||
##############
|
||||
|
||||
.. note::
|
||||
La documentación no es compatible actualmente con el idioma español en esta página.
|
||||
|
||||
Por favor, siéntase libre de enviarnos un pull request en
|
||||
`Github <https://github.com/cakephp/bake>`_ o utilizar el botón **Improve this Doc** para proponer directamente los cambios.
|
||||
|
||||
Usted puede hacer referencia a la versión en Inglés en el menú de selección superior
|
||||
para obtener información sobre el tema de esta página.
|
||||
|
||||
.. _creating-a-bake-theme:
|
||||
|
||||
.. meta::
|
||||
:title lang=es: Extending Bake
|
||||
:keywords lang=es: command line interface,development,bake view, bake template syntax,erb tags,asp tags,percent tags
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
Consola bake
|
||||
############
|
||||
|
||||
La consola bake de CakePHP es otro esfuerzo para preparar y ejecutar CakePHP rápidamente.
|
||||
|
||||
La consola bake puede crear cualquiera de los ingredientes básicos de CakePHP:
|
||||
modelos, behaviours, vistas, helpers, controladores, componentes, casos de
|
||||
prueba, fixtures y plugins.
|
||||
|
||||
Y no hablamos sólo de esqueletos de clases: Bake puede crear una aplicación
|
||||
totalmente funcional en solo un par de minutos.
|
||||
|
||||
De hecho, Bake es un paso natural a dar una vez ha sido creado el esqueleto de
|
||||
la aplicación.
|
||||
|
||||
Instalación
|
||||
===========
|
||||
|
||||
Antes de intentar utilizar o extender bake asegúrate de que está instalado en tu
|
||||
aplicación.
|
||||
|
||||
Bake está incluido como un plugin que puedes instalar con Composer::
|
||||
|
||||
composer require --dev cakephp/bake:~1.0
|
||||
|
||||
La instrucción anterior instalará bake como una dependencia de desarrollo. Esto
|
||||
significa que no será instalado cuando hagas despliegues en producción.
|
||||
|
||||
.. meta::
|
||||
:title lang=es: Consola Bake
|
||||
:keywords lang=es: interfaz de línea de comando,desarrollo,bake vista, bake sintaxis plantilla,erb tags,asp tags,percent tags
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
Crear código con Bake
|
||||
#####################
|
||||
|
||||
La consola de CAKE se ejecuta usando PHP CLI (command line interface).
|
||||
Si tiene problemas para ejecutar el script, asegurese de:
|
||||
|
||||
#. Tener instalado el PHP CLI y que estén los módulos correspondientes
|
||||
habilitados (ej: MySQL y intl).
|
||||
#. Si el host de base de datos es 'localhost', intente realizar la conexión con
|
||||
el ip '127.0.0.1'. En algunos casos PHP CLI tiene problemas al referenciar
|
||||
por nombre de host (localhost).
|
||||
#. Dependiendo de como esté configurado su equipo, la ejecución del comando
|
||||
CAKE BAKE (cake bash script) puede requerir permisos de ejecución al
|
||||
lanzar ``bin/cake bake``.
|
||||
|
||||
Antes de comenzar la ejecución, asegúrese de disponer al menos de una conexión
|
||||
a una base de datos configurada.
|
||||
|
||||
Para comenzar con la ejecución del comando debe abrir la consola de windows
|
||||
y ejecutar "Cake Bake"
|
||||
|
||||
#. Ir a Inicio (Start) > Ejecutar (Run)
|
||||
#. Escribir "cmd" y presionar 'Enter'
|
||||
#. Navegar hasta llegar a la carpeta de instalación de cake
|
||||
#. Acceder a la carpeta 'bin'
|
||||
#. Escribir 'Cake bake' lo cual deberá devolver un listado con todas las
|
||||
tareas/actividades disponibles.
|
||||
|
||||
El resultado debería ser algo similar a lo siguiente::
|
||||
|
||||
$ bin/cake bake
|
||||
|
||||
Welcome to CakePHP v3.1.6 Console
|
||||
---------------------------------------------------------------
|
||||
App : src
|
||||
Path: /var/www/cakephp.dev/src/
|
||||
PHP: 5.5.8
|
||||
---------------------------------------------------------------
|
||||
The following commands can be used to generate skeleton code for your application.
|
||||
|
||||
Available bake commands:
|
||||
|
||||
- all
|
||||
- behavior
|
||||
- cell
|
||||
- component
|
||||
- controller
|
||||
- fixture
|
||||
- form
|
||||
- helper
|
||||
- mailer
|
||||
- migration
|
||||
- migration_snapshot
|
||||
- model
|
||||
- plugin
|
||||
- shell
|
||||
- shell-helper
|
||||
- template
|
||||
- test
|
||||
|
||||
By using 'cake bake [name]' you can invoke a specific bake task.
|
||||
|
||||
Puede obtener más información sobre lo que realiza cada una de las actividades
|
||||
y sus opciones usando el parametro '--help' option::
|
||||
|
||||
$ bin/cake bake controller --help
|
||||
|
||||
Welcome to CakePHP v3.1.6 Console
|
||||
---------------------------------------------------------------
|
||||
App : src
|
||||
Path: /var/www/cakephp.dev/src/
|
||||
---------------------------------------------------------------
|
||||
Bake a controller skeleton.
|
||||
|
||||
Usage:
|
||||
cake bake controller [subcommand] [options] [<name>]
|
||||
|
||||
Subcommands:
|
||||
|
||||
all Bake all controllers with CRUD methods.
|
||||
|
||||
To see help on a subcommand use `cake bake controller [subcommand] --help`
|
||||
|
||||
Options:
|
||||
|
||||
--help, -h Display this help.
|
||||
--verbose, -v Enable verbose output.
|
||||
--quiet, -q Enable quiet output.
|
||||
--plugin, -p Plugin to bake into.
|
||||
--force, -f Force overwriting existing files without prompting.
|
||||
--connection, -c The datasource connection to get data from.
|
||||
(default: default)
|
||||
--theme, -t The theme to use when baking code.
|
||||
--components The comma separated list of components to use.
|
||||
--helpers The comma separated list of helpers to use.
|
||||
--prefix The namespace/routing prefix to use.
|
||||
--no-test Do not generate a test skeleton.
|
||||
--no-actions Do not generate basic CRUD action methods.
|
||||
|
||||
Arguments:
|
||||
|
||||
name Name of the controller to bake. Can use Plugin.name to bake
|
||||
controllers into plugins. (optional)
|
||||
|
||||
Temas Bake / Templates
|
||||
======================
|
||||
|
||||
La opción ``theme`` es genérica para todos los comandos bake y permite cambiar los
|
||||
templates de bake utilizados para generar los archivos finales. Para crear sus
|
||||
propios templates, ver :ref:`bake theme creation documentation
|
||||
<creating-a-bake-theme>`.
|
||||
|
||||
.. meta::
|
||||
:title lang=es: Crear código con Bake
|
||||
:keywords lang=es: interfaz de línea de comando, aplicación funcional, base de datos, configuración de base de datos, bash script, ingredientes básicos, proyecto, modelo, path, crear código, generación de código, scaffolding, usuarios windows, archivo de configuración, pocos minutos, configurar, iew, shell, modelos, running, mysql
|
||||
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
import sys, os
|
||||
|
||||
# Append the top level directory of the docs, so we can import from the config dir.
|
||||
sys.path.insert(0, os.path.abspath('..'))
|
||||
|
||||
# Pull in all the configuration options defined in the global config file..
|
||||
from config.all import *
|
||||
|
||||
language = 'fr'
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
:caption: CakePHP Bake
|
||||
|
||||
/index
|
||||
/usage
|
||||
/development
|
||||
+351
@@ -0,0 +1,351 @@
|
||||
Etendre Bake
|
||||
############
|
||||
|
||||
Bake dispose d'une architecture extensible qui permet à votre application ou
|
||||
à vos plugins de modifier ou ajouter la fonctionnalité de base. Bake utilise une
|
||||
classe de vue dédiée qui n'utilise pas la syntaxe PHP standard.
|
||||
|
||||
Events de Bake
|
||||
==============
|
||||
|
||||
Comme une classe de vue, ``BakeView`` envoie les mêmes events que toute autre
|
||||
classe de vue, ainsi qu'un event initialize supplémentaire. Cependant,
|
||||
alors que les classes de vue standard utilisent le préfixe d'event
|
||||
"View.", ``BakeView`` utilise le préfixe d'event "Bake.".
|
||||
|
||||
L'event initialize peut être utilisé pour faire des changements qui
|
||||
s'appliquent à toutes les sorties fabriquées avec bake, par exemple pour ajouter
|
||||
un autre helper à la classe de vue bake, cet event peut être utilisé::
|
||||
|
||||
<?php
|
||||
// config/bootstrap_cli.php
|
||||
|
||||
use Cake\Event\Event;
|
||||
use Cake\Event\EventManager;
|
||||
|
||||
EventManager::instance()->on('Bake.initialize', function (Event $event) {
|
||||
$view = $event->getSubject();
|
||||
|
||||
// Dans mes templates de bake, permet l'utilisation du helper MySpecial
|
||||
$view->loadHelper('MySpecial', ['some' => 'config']);
|
||||
|
||||
// Et ajoute une variable $author pour qu'elle soit toujours disponible
|
||||
$view->set('author', 'Andy');
|
||||
|
||||
});
|
||||
|
||||
Si vous souhaitez modifier bake à partir d'un autre plugin, mettre les events
|
||||
de bake de votre plugin dans le fichier ``config/bootstrap.php`` du plugin est
|
||||
une bonne idée.
|
||||
|
||||
Les events de bake peuvent être pratiques pour faire de petits changements dans
|
||||
les templates existants. Par exemple, pour changer les noms de variables
|
||||
utilisés lors de la création avec bake de fichiers de controller/template, on
|
||||
pourra utiliser une fonction qui écoute ``Bake.beforeRender`` pour modifier les
|
||||
variables utilisées dans les templates de bake::
|
||||
|
||||
<?php
|
||||
// config/bootstrap_cli.php
|
||||
|
||||
use Cake\Event\Event;
|
||||
use Cake\Event\EventManager;
|
||||
|
||||
EventManager::instance()->on('Bake.beforeRender', function (Event $event) {
|
||||
$view = $event->getSubject();
|
||||
|
||||
// Utilise $rows pour les principales variables de données dans les indexes
|
||||
if ($view->get('pluralName')) {
|
||||
$view->set('pluralName', 'rows');
|
||||
}
|
||||
if ($view->get('pluralVar')) {
|
||||
$view->set('pluralVar', 'rows');
|
||||
}
|
||||
|
||||
// Utilise $theOne pour les principales variable de données dans les view/edit
|
||||
if ($view->get('singularName')) {
|
||||
$view->set('singularName', 'theOne');
|
||||
}
|
||||
if ($view->get('singularVar')) {
|
||||
$view->set('singularVar', 'theOne');
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
Vous pouvez aussi scoper les events ``Bake.beforeRender`` et
|
||||
``Bake.afterRender`` dans un fichier généré spécifique. Par exemple, si vous
|
||||
souhaitez ajouter des actions spécifiques à votre UsersController quand vous le
|
||||
générez à partir d'un fichier **Controller/controller.ctp**, vous pouvez
|
||||
utiliser l'event suivant::
|
||||
|
||||
<?php
|
||||
// config/bootstrap_cli.php
|
||||
|
||||
use Cake\Event\Event;
|
||||
use Cake\Event\EventManager;
|
||||
use Cake\Utility\Hash;
|
||||
|
||||
EventManager::instance()->on(
|
||||
'Bake.beforeRender.Controller.controller',
|
||||
function (Event $event) {
|
||||
$view = $event->subject;
|
||||
if ($view->viewVars['name'] == 'Users') {
|
||||
// ajouter les actions login et logout au controller Users
|
||||
$view->viewVars['actions'] = [
|
||||
'login',
|
||||
'logout',
|
||||
'index',
|
||||
'view',
|
||||
'add',
|
||||
'edit',
|
||||
'delete'
|
||||
];
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
En scopant les écouteurs d'event vers des templates de bake spécifiques, vous
|
||||
pouvez simplifier votre logique d'event liée à bake et fournir des callbacks
|
||||
qui sont plus faciles à tester.
|
||||
|
||||
Syntaxe de Template de Bake
|
||||
===========================
|
||||
|
||||
Les fichiers de template de Bake utilisent les balises erb-style (``<% %>``)
|
||||
pour indiquer la logique des templates, et traitent le reste, y compris les
|
||||
balises php, comme du texte.
|
||||
|
||||
.. note::
|
||||
|
||||
Les fichiers de template de Bake n'utilisent pas, et sont insensibles aux
|
||||
``asp_tags`` de la configuration de php ini.
|
||||
|
||||
``BakeView`` intègre les balises suivantes:
|
||||
|
||||
* ``<%`` Une balise php ouverte de template de Bake
|
||||
* ``%>`` Une balise php fermante de template de Bake
|
||||
* ``<%=`` Une balise php de short-echo de template de Bake
|
||||
* ``<%-`` Une balise php ouverte de template de Bake, enlevant tout espace
|
||||
en tête avant la balise
|
||||
* ``-%>`` Une balise php fermante de template de Bake, enlevant les espaces
|
||||
à a fin après la balise
|
||||
|
||||
Une façon de voir/comprendre la façon dont les templates de Bake fonctionne,
|
||||
spécialement quand on essaie de modifier les fichiers de template de bake, est
|
||||
de créer avec bake une classe et de comparer le template utilisé avec le
|
||||
template déjà présent dans le dossier **tmp/bake** de votre application.
|
||||
|
||||
Ainsi, par exemple, pour créer avec bake un shell comme ceci:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
bin/cake bake shell Foo
|
||||
|
||||
Le template utilisé
|
||||
(**vendor/cakephp/cakephp/src/Template/Bake/Shell/shell.ctp**)
|
||||
ressemble à ceci::
|
||||
|
||||
<?php
|
||||
namespace <%= $namespace %>\Shell;
|
||||
|
||||
use Cake\Console\Shell;
|
||||
|
||||
/**
|
||||
* <%= $name %> shell command.
|
||||
*/
|
||||
class <%= $name %>Shell extends Shell
|
||||
{
|
||||
|
||||
/**
|
||||
* main() method.
|
||||
*
|
||||
* @return bool|int Success or error code.
|
||||
*/
|
||||
public function main()
|
||||
{
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Le fichier template déjà présent (pre-processed)
|
||||
(**tmp/bake/Bake-Shell-shell-ctp.php**), qui est le fichier réellement
|
||||
rendu, ressemble à ceci::
|
||||
|
||||
<CakePHPBakeOpenTagphp
|
||||
namespace <?= $namespace ?>\Shell;
|
||||
|
||||
use Cake\Console\Shell;
|
||||
|
||||
/**
|
||||
* <?= $name ?> shell command.
|
||||
*/
|
||||
class <?= $name ?>Shell extends Shell
|
||||
{
|
||||
|
||||
/**
|
||||
* main() method.
|
||||
*
|
||||
* @return bool|int Success or error code.
|
||||
*/
|
||||
public function main()
|
||||
{
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Et la classe résultante construite avec bake (**src/Shell/FooShell.php**)
|
||||
ressemble à ceci::
|
||||
|
||||
<?php
|
||||
namespace App\Shell;
|
||||
|
||||
use Cake\Console\Shell;
|
||||
|
||||
/**
|
||||
* Foo shell command.
|
||||
*/
|
||||
class FooShell extends Shell
|
||||
{
|
||||
|
||||
/**
|
||||
* main() method.
|
||||
*
|
||||
* @return bool|int Success or error code.
|
||||
*/
|
||||
public function main()
|
||||
{
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
.. _creating-a-bake-theme:
|
||||
|
||||
Créer un theme de bake
|
||||
======================
|
||||
|
||||
Si vous souhaitez modifier la sortie du HTML produit par la commande "bake",
|
||||
vous pouvez créer votre propre 'template' de bake qui vous permet de remplacer
|
||||
certaine ou toute partie des templates que bake utilise. Pour créer un nouveau
|
||||
template de bake, faîtes ce qui suit:
|
||||
|
||||
#. Créez un nouveau plugin avec Bake. Le nom du plugin est le nom du 'theme' de
|
||||
Bake
|
||||
#. Créez un nouveau répertoire **plugins/[name]/src/Template/Bake/Template/**.
|
||||
#. Copiez tout template que vous souhaitez changer à partir de
|
||||
**vendor/cakephp/bake/src/Template/Bake/Template** vers les
|
||||
fichiers correspondants dans votre plugin.
|
||||
#. Quand vous lancez bake, utilisez l'option ``--theme`` pour spécifier le
|
||||
theme de bake que vous souhaitez utiliser. Pour éviter d'avoir à spécifier
|
||||
cette option dans chaque appel, vous pouvez aussi définir votre thème
|
||||
personnalisé à utiliser comme thème par défaut::
|
||||
|
||||
<?php
|
||||
// in config/bootstrap.php or config/bootstrap_cli.php
|
||||
Configure::write('Bake.theme', 'MyTheme');
|
||||
|
||||
Personnaliser les Templates de Bake
|
||||
===================================
|
||||
|
||||
Si vous souhaitez modifier la sortie par défaut produite par la commande "bake",
|
||||
vous pouvez créer vos propres templates de bake dans votre application. Cette
|
||||
façon n'utilise pas l'option ``--theme`` dans la ligne de commande lors de
|
||||
l'exécution de bake. La meilleure façon de faire est de faire ce qui suit:
|
||||
|
||||
#. Créer un nouveau répertoire **/src/Template/Bake/**.
|
||||
#. Copier tout template que vous souhaitez surcharger de
|
||||
**vendor/cakephp/bake/src/Template/Bake/** vers les fichiers correspondants
|
||||
dans votre application.
|
||||
|
||||
Créer de Nouvelles Options de Commande pour Bake
|
||||
================================================
|
||||
|
||||
Il est possible d'ajouter de nouvelles options de commandes de bake, ou de
|
||||
surcharger celles fournies par CakePHP en créant des tâches dans votre
|
||||
application ou dans vos plugins. En étendant ``Cake\Shell\Task\BakeTask``, bake
|
||||
va trouver votre nouvelle tâche et l'inclure comme faisant partie de bake.
|
||||
|
||||
En exemple, nous allons faire une tâche qui créé une classe arbitraire foo.
|
||||
D'abord créez le fichier de tâche **src/Shell/Task/FooTask.php**. Nous
|
||||
étendrons le ``SimpleBakeTask`` pour l'instant puisque notre tâche shell sera
|
||||
simple. ``SimpleBakeTask`` est abstraite et nous impose de définir 3 méthodes
|
||||
qui disent à bake comment la tâche est appelée, l'endroit où devront se trouver
|
||||
les fichiers qu'il va générer, et le template à utiliser. Notre fichier
|
||||
FooTask.php devra ressembler à ceci::
|
||||
|
||||
<?php
|
||||
namespace App\Shell\Task;
|
||||
|
||||
use Cake\Shell\Task\SimpleBakeTask;
|
||||
|
||||
class FooTask extends SimpleBakeTask
|
||||
{
|
||||
public $pathFragment = 'Foo/';
|
||||
|
||||
public function name()
|
||||
{
|
||||
return 'foo';
|
||||
}
|
||||
|
||||
public function fileName($name)
|
||||
{
|
||||
return $name . 'Foo.php';
|
||||
}
|
||||
|
||||
public function template()
|
||||
{
|
||||
return 'foo';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Une fois que le fichier a été créé, nous devons créer un template que bake peut
|
||||
utiliser pour la génération de code. Créez
|
||||
**src/Template/Bake/foo.ctp**. Dans ce fichier, nous
|
||||
ajouterons le contenu suivant::
|
||||
|
||||
<?php
|
||||
namespace <%= $namespace %>\Foo;
|
||||
|
||||
/**
|
||||
* <%= $name %> foo
|
||||
*/
|
||||
class <%= $name %>Foo
|
||||
{
|
||||
// Add code.
|
||||
}
|
||||
|
||||
Vous devriez maintenant voir votre nouvelle tâche dans l'affichage de
|
||||
``bin/cake bake``. Vous pouvez lancer votre nouvelle tâche en exécutant
|
||||
``bin/cake bake foo Example``.
|
||||
Cela va générer une nouvelle classe ``ExampleFoo`` dans
|
||||
**src/Foo/ExampleFoo.php** que votre application va
|
||||
pouvoir utiliser.
|
||||
|
||||
Si vous souhaitez que votre appel à ``bake`` crée également un fichier de test
|
||||
pour la classe ``ExampleFoo``, vous devrez surcharger la méthode ``bakeTest()``
|
||||
dans la classe ``FooTask`` pour y définir le suffixe et le namespace de la
|
||||
classe de votre nom de commande personnalisée::
|
||||
|
||||
public function bakeTest($className)
|
||||
{
|
||||
if (!isset($this->Test->classSuffixes[$this->name()])) {
|
||||
$this->Test->classSuffixes[$this->name()] = 'Foo';
|
||||
}
|
||||
|
||||
$name = ucfirst($this->name());
|
||||
if (!isset($this->Test->classTypes[$name])) {
|
||||
$this->Test->classTypes[$name] = 'Foo';
|
||||
}
|
||||
|
||||
return parent::bakeTest($className);
|
||||
}
|
||||
|
||||
* Le **suffixe de classe** sera ajouté après le nom passé à ``bake``. Dans le
|
||||
cadre de l'exemple ci-dessus, cela créerait un fichier ``ExampleFooTest.php``.
|
||||
* Le **type de classe** sera le sous-namespace utilisé pour atteindre votre
|
||||
fichier (relatif à l'application ou au plugin dans lequel vous faites le
|
||||
``bake``). Dans le cadre de l'exemple ci-dessus, cela créerait le test avec le
|
||||
namespace ``App\Test\TestCase\Foo``.
|
||||
|
||||
.. meta::
|
||||
:title lang=fr: Etendre Bake
|
||||
:keywords lang=fr: interface ligne de commande,development,bake view, bake template syntax,erb tags,asp tags,percent tags
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
Console Bake
|
||||
############
|
||||
|
||||
La console Bake de CakePHP est un autre outil permettant de réaliser son
|
||||
application rapidement. La console Bake peut créer chacun des ingrédients
|
||||
basiques de CakePHP : models, behaviors, views, helpers, controllers,
|
||||
components, cas de tests, fixtures et plugins. Et nous ne parlons pas
|
||||
seulement des squelettes de classes : Bake peut créer une application
|
||||
fonctionnelle complète en seulement quelques minutes. En réalité, Bake est une
|
||||
étape naturelle à suivre une fois qu'une application a été prototypée.
|
||||
|
||||
Installation
|
||||
============
|
||||
|
||||
Avant d'essayer d'utiliser ou d'étendre bake, assurez-vous qu'il est installé
|
||||
dans votre application. Bake est disponible en tant que plugin que vous pouvez
|
||||
installer avec Composer::
|
||||
|
||||
composer require --dev cakephp/bake:~1.0
|
||||
|
||||
Ceci va installer bake en tant que dépendance de développement. Cela signifie
|
||||
qu'il ne sera pas installé lors d'un déploiement en production.
|
||||
|
||||
.. meta::
|
||||
:title lang=fr: Console Bake
|
||||
:keywords lang=fr: interface ligne de commande,development,bake view, bake template syntaxe,erb tags,asp tags,percent tags
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
Génération de Code avec Bake
|
||||
############################
|
||||
|
||||
Suivant la configuration de votre installation, vous devrez peut être donner
|
||||
les droits d'exécution au script bash cake ou l'appeler avec la commande
|
||||
``./bin/cake bake``.
|
||||
La console cake est exécutée en utilisant le CLI PHP
|
||||
(Interface de Ligne de Commande). Si vous avez des problèmes en exécutant ce
|
||||
script, vérifiez que :
|
||||
|
||||
#. le CLI PHP est installé et qu'il a les bons modules activés (ex: MySQL, intl).
|
||||
#. Certains utilisateurs peuvent aussi rencontrer des problèmes si la base de
|
||||
données host est 'localhost' et devront essayer '127.0.0.1' à la place.
|
||||
#. Selon la configuration de votre ordinateur, vous devrez peut-être permettre
|
||||
l'exécution du script bash pour permettre de lancer ``bin/cake bake``.
|
||||
|
||||
Avant de lancer bake, vous devrez vous assurer qu'au moins une connection à une
|
||||
base de données est configurée.
|
||||
|
||||
Si vous exécutez la commande sans argument, ``bin/cake bake`` affichera la liste
|
||||
des tâches disponibles. Vous devriez voir quelque chose comme ceci::
|
||||
|
||||
$ bin/cake bake
|
||||
|
||||
Welcome to CakePHP v3.x.x Console
|
||||
---------------------------------------------------------------
|
||||
App : src
|
||||
Path: /var/www/cakephp.dev/src/
|
||||
---------------------------------------------------------------
|
||||
Les commandes suivantes avec lesquelles vous pouvez générer un squelette de
|
||||
code pour votre application.
|
||||
|
||||
Les commandes disponibles de bake:
|
||||
|
||||
- all
|
||||
- behavior
|
||||
- cell
|
||||
- component
|
||||
- controller
|
||||
- fixture
|
||||
- form
|
||||
- helper
|
||||
- mailer
|
||||
- migration
|
||||
- migration_snapshot
|
||||
- model
|
||||
- plugin
|
||||
- shell
|
||||
- shell-helper
|
||||
- template
|
||||
- test
|
||||
|
||||
En utilisant `cake bake [name]` vous pouvez faire appel à une tâche
|
||||
spécifique de bake.
|
||||
|
||||
Vous pouvez obtenir plus d'informations sur ce que chaque tâche fait et les
|
||||
options disponibles en utilisant l'option ``--help``::
|
||||
|
||||
$ bin/cake bake controller --help
|
||||
|
||||
Welcome to CakePHP v3.x.x Console
|
||||
---------------------------------------------------------------
|
||||
App : src
|
||||
Path: /var/www/cakephp.dev/src/
|
||||
---------------------------------------------------------------
|
||||
Bake a controller skeleton.
|
||||
|
||||
Usage:
|
||||
cake bake controller [subcommand] [options] [<name>]
|
||||
|
||||
Subcommands:
|
||||
|
||||
all Bake all controllers with CRUD methods.
|
||||
|
||||
To see help on a subcommand use `cake bake controller [subcommand] --help`
|
||||
|
||||
Options:
|
||||
|
||||
--help, -h Display this help.
|
||||
--verbose, -v Enable verbose output.
|
||||
--quiet, -q Enable quiet output.
|
||||
--plugin, -p Plugin to bake into.
|
||||
--force, -f Force overwriting existing files without prompting.
|
||||
--connection, -c The datasource connection to get data from.
|
||||
(default: default)
|
||||
--theme, -t The theme to use when baking code.
|
||||
--components The comma separated list of components to use.
|
||||
--helpers The comma separated list of helpers to use.
|
||||
--prefix The namespace/routing prefix to use.
|
||||
--no-test Do not generate a test skeleton.
|
||||
--no-actions Do not generate basic CRUD action methods.
|
||||
|
||||
Arguments:
|
||||
|
||||
name Name of the controller to bake. Can use Plugin.name to bake
|
||||
controllers into plugins. (optional)
|
||||
|
||||
Themes de Bake
|
||||
==============
|
||||
|
||||
L'option theme est commune à toutes les commandes de bake, et permet de changer
|
||||
les fichiers de template utilisés lors de la création avec bake. Pour créer vos
|
||||
propres templates, référez-vous :ref:`à la documentation sur la création de
|
||||
theme bake <creating-a-bake-theme>`.
|
||||
|
||||
.. meta::
|
||||
:title lang=fr: Génération de Code avec Bake
|
||||
:keywords lang=fr: interface ligne de commande,application fonctionnelle,base de données,configuration base de données,bash script,ingredients basiques,project,model,path path,génération de code,scaffolding,windows users,configuration file,few minutes,config,iew,shell,models,running,mysql
|
||||
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
import sys, os
|
||||
|
||||
# Append the top level directory of the docs, so we can import from the config dir.
|
||||
sys.path.insert(0, os.path.abspath('..'))
|
||||
|
||||
# Pull in all the configuration options defined in the global config file..
|
||||
from config.all import *
|
||||
|
||||
language = 'ja'
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
:caption: CakePHP Bake
|
||||
|
||||
/index
|
||||
/usage
|
||||
/development
|
||||
+301
@@ -0,0 +1,301 @@
|
||||
Bake の拡張
|
||||
###########
|
||||
|
||||
Bake は、アプリケーションやプラグインが基本機能に対して変更または追加を可能にする
|
||||
拡張可能なアーキテクチャーを備えています。Bake は、 `Twig <https://twig.symfony.com/>`_
|
||||
テンプレートエンジンを使用したビュークラスを利用します。
|
||||
|
||||
Bake イベント
|
||||
=============
|
||||
|
||||
``BakeView`` は、ビュークラスとして、他のビュークラスと同様のイベントに加え、
|
||||
1つの特別な初期化 (initialize) イベントを発します。しかし、一方で標準ビュークラスは、
|
||||
イベントのプレフィックス "View." を使用しますが、 ``BakeView`` は、
|
||||
イベントのプレフィックス "Bake." を使用しています。
|
||||
|
||||
初期化イベントは、すべての bake の出力に対して変更を加えるために使用できます。
|
||||
例えば、bake ビュークラスに他のヘルパーを追加するためにこのイベントは使用されます。 ::
|
||||
|
||||
<?php
|
||||
// config/bootstrap_cli.php
|
||||
|
||||
use Cake\Event\Event;
|
||||
use Cake\Event\EventManager;
|
||||
|
||||
EventManager::instance()->on('Bake.initialize', function (Event $event) {
|
||||
$view = $event->getSubject();
|
||||
|
||||
// bake テンプレートの中で MySpecial ヘルパーの使用を可能にします
|
||||
$view->loadHelper('MySpecial', ['some' => 'config']);
|
||||
|
||||
// そして、$author 変数を利用可能にするために追加
|
||||
$view->set('author', 'Andy');
|
||||
|
||||
});
|
||||
|
||||
別のプラグインの中から bake を変更したい場合は、プラグインの ``config/bootstrap.php``
|
||||
ファイルでプラグインの Bake イベントを置くことは良いアイデアです。
|
||||
|
||||
Bake イベントは、既存のテンプレートに小さな変更を行うための便利なことができます。
|
||||
例えば、コントローラーやテンプレートファイルを bake する際に使用される変数名を
|
||||
変更するために、bake テンプレートで使用される変数を変更するために
|
||||
``Bake.beforeRender`` で呼び出される関数を使用することができます。 ::
|
||||
|
||||
<?php
|
||||
// config/bootstrap_cli.php
|
||||
|
||||
use Cake\Event\Event;
|
||||
use Cake\Event\EventManager;
|
||||
|
||||
EventManager::instance()->on('Bake.beforeRender', function (Event $event) {
|
||||
$view = $event->getSubject();
|
||||
|
||||
// indexes の中のメインデータ変数に $rows を使用
|
||||
if ($view->get('pluralName')) {
|
||||
$view->set('pluralName', 'rows');
|
||||
}
|
||||
if ($view->get('pluralVar')) {
|
||||
$view->set('pluralVar', 'rows');
|
||||
}
|
||||
|
||||
// view と edit の中のメインデータ変数に $theOne を使用
|
||||
if ($view->get('singularName')) {
|
||||
$view->set('singularName', 'theOne');
|
||||
}
|
||||
if ($view->get('singularVar')) {
|
||||
$view->set('singularVar', 'theOne');
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
特定の生成されたファイルへの ``Bake.beforeRender`` と ``Bake.afterRender``
|
||||
イベントを指定することもあるでしょう。例えば、
|
||||
**Controller/controller.twig** ファイルから生成する際、 UsersController
|
||||
に特定のアクションを追加したい場合、以下のイベントを使用することができます。 ::
|
||||
|
||||
<?php
|
||||
// config/bootstrap_cli.php
|
||||
|
||||
use Cake\Event\Event;
|
||||
use Cake\Event\EventManager;
|
||||
use Cake\Utility\Hash;
|
||||
|
||||
EventManager::instance()->on(
|
||||
'Bake.beforeRender.Controller.controller',
|
||||
function (Event $event) {
|
||||
$view = $event->getSubject();
|
||||
if ($view->viewVars['name'] == 'Users') {
|
||||
// Users コントローラーに login と logout を追加
|
||||
$view->viewVars['actions'] = [
|
||||
'login',
|
||||
'logout',
|
||||
'index',
|
||||
'view',
|
||||
'add',
|
||||
'edit',
|
||||
'delete'
|
||||
];
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
特定の bake テンプレートのためのイベントリスナーを指定することによって、
|
||||
bake 関連のイベント・ロジックを簡素化し、テストするのが容易であるコールバックを
|
||||
提供することができます。
|
||||
|
||||
Bake テンプレート構文
|
||||
=====================
|
||||
|
||||
Bake テンプレートファイルは、 `Twig <https://twig.symfony.com/doc/2.x/>`__
|
||||
テンプレート構文を使用します。
|
||||
|
||||
bake テンプレートがどのように動作するかを確認/理解する一つの方法は、
|
||||
bake テンプレートファイルを変更しようとする場合は特に、クラスを bake して、
|
||||
アプリケーションの **tmp/bake** フォルダー内に残っている前処理されたテンプレートファイルを
|
||||
使ったテンプレートと比較することです。
|
||||
|
||||
だから、例えば、以下のようにシェルを bake した場合:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
bin/cake bake shell Foo
|
||||
|
||||
(**vendor/cakephp/bake/src/Template/Bake/Shell/shell.twig**) を使用した
|
||||
テンプレートは、以下のようになります。 ::
|
||||
|
||||
<?php
|
||||
namespace {{ namespace }}\Shell;
|
||||
|
||||
use Cake\Console\Shell;
|
||||
|
||||
/**
|
||||
* {{ name }} shell command.
|
||||
*/
|
||||
class {{ name }}Shell extends Shell
|
||||
{
|
||||
/**
|
||||
* main() method.
|
||||
*
|
||||
* @return bool|int Success or error code.
|
||||
*/
|
||||
public function main()
|
||||
{
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
そして、 bake で得られたクラス (**src/Shell/FooShell.php**) は、
|
||||
このようになります。 ::
|
||||
|
||||
<?php
|
||||
namespace App\Shell;
|
||||
|
||||
use Cake\Console\Shell;
|
||||
|
||||
/**
|
||||
* Foo shell command.
|
||||
*/
|
||||
class FooShell extends Shell
|
||||
{
|
||||
/**
|
||||
* main() method.
|
||||
*
|
||||
* @return bool|int Success or error code.
|
||||
*/
|
||||
public function main()
|
||||
{
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
.. note::
|
||||
|
||||
バージョン 1.5.0 より前の bake は、 .ctp テンプレートファイルでカスタム erb スタイルのタグを
|
||||
使用していました。
|
||||
|
||||
* ``<%`` Bake テンプレートの PHP 開始タグ
|
||||
* ``%>`` Bake テンプレートの PHP 終了タグ
|
||||
* ``<%=`` Bake テンプレートの PHP ショートエコータグ
|
||||
* ``<%-`` Bake テンプレートの PHP 開始タグ、タグの前に、先頭の空白を除去
|
||||
* ``-%>`` Bake テンプレートの PHP 終了タグ、タグの後に末尾の空白を除去
|
||||
|
||||
.. _creating-a-bake-theme:
|
||||
|
||||
Bake テーマの作成
|
||||
=================
|
||||
|
||||
"bake" コマンドによって生成された出力を変更したい場合、bake が使用するテンプレートの
|
||||
一部または全部を置き換えることができる、独自の bake の「テーマ」を作成することができます。
|
||||
これを行うための最善の方法は、次のとおりです。
|
||||
|
||||
#. 新しいプラグインを bake します。プラグインの名前は bake の「テーマ」名になります。
|
||||
#. 新しいディレクトリー **plugins/[name]/src/Template/Bake/Template/** を作成します。
|
||||
#. **vendor/cakephp/bake/src/Template/Bake/Template** から上書きしたい
|
||||
テンプレートをあなたのプラグインの中の適切なファイルにコピーしてください。
|
||||
#. bake を実行するときに、必要であれば、 bake のテーマを指定するための ``--theme``
|
||||
オプションを使用してください。各呼び出しでこのオプションを指定しなくても済むように、
|
||||
カスタムテーマをデフォルトテーマとして使用するように設定することもできます。 ::
|
||||
|
||||
<?php
|
||||
// config/bootstrap.php または config/bootstrap_cli.php の中で
|
||||
Configure::write('Bake.theme', 'MyTheme');
|
||||
|
||||
Bake テンプレートのカスタマイズ
|
||||
===============================
|
||||
|
||||
"bake" コマンドによって生成されるデフォルトの出力を変更したい場合、アプリケーションで独自の
|
||||
bake テンプレートを作成することができます。この方法では、bake する際、コマンドラインで
|
||||
``--theme`` オプションを使用していません。これを行うための最善の方法は、次のとおりです。
|
||||
|
||||
#. 新しいディレクトリー **/src/Template/Bake/** を作成します。
|
||||
#. **vendor/cakephp/bake/src/Template/Bake/** から上書きしたいテンプレートを
|
||||
あなたのアプリケーションの中の適切なファイルにコピーします。
|
||||
|
||||
Bake コマンドオプションの新規作成
|
||||
=================================
|
||||
|
||||
あなたのアプリケーションやプラグインでタスクを作成することによって、新しい bake コマンドの
|
||||
オプションを追加したり、CakePHP が提供するオプションを上書きすることが可能です。
|
||||
``Bake\Shell\Task\BakeTask`` を継承することで、bake は、あなたの新しいタスクを見つけて
|
||||
bake の一部としてそれを含めます。
|
||||
|
||||
例として、任意の foo クラスを作成するタスクを作ります。
|
||||
まず、 **src/Shell/Task/FooTask.php** タスクファイルを作成します。
|
||||
私たちのシェルタスクが単純になるように、 ``SimpleBakeTask`` を継承します。
|
||||
``SimpleBakeTask`` は抽象クラスで、どのタスクが呼ばれるか、どこにファイルを生成するか、
|
||||
どのテンプレートを使用するかを bake に伝える3つのメソッドを定義することが必要です。
|
||||
FooTask.php ファイルは次のようになります。 ::
|
||||
|
||||
<?php
|
||||
namespace App\Shell\Task;
|
||||
|
||||
use Bake\Shell\Task\SimpleBakeTask;
|
||||
|
||||
class FooTask extends SimpleBakeTask
|
||||
{
|
||||
public $pathFragment = 'Foo/';
|
||||
|
||||
public function name()
|
||||
{
|
||||
return 'foo';
|
||||
}
|
||||
|
||||
public function fileName($name)
|
||||
{
|
||||
return $name . 'Foo.php';
|
||||
}
|
||||
|
||||
public function template()
|
||||
{
|
||||
return 'foo';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
このファイルが作成されたら、コードを生成する際に bake 使用することができるテンプレートを
|
||||
作成する必要があります。 **src/Template/Bake/foo.twig** を作成してください。
|
||||
このファイルに、以下の内容を追加します。 ::
|
||||
|
||||
<?php
|
||||
namespace {{ namespace }}\Foo;
|
||||
|
||||
/**
|
||||
* {{ name }} foo
|
||||
*/
|
||||
class {{ name }}Foo
|
||||
{
|
||||
// コードを追加。
|
||||
}
|
||||
|
||||
これで、``bin/cake bake`` の出力に新しいタスクが表示されるはずです。
|
||||
``bin/cake bake foo Example`` を実行して、新しいタスクを実行することができます。
|
||||
これは、使用するアプリケーションの **src/Foo/ExampleFoo.php** で
|
||||
新しい ``ExampleFoo`` クラスを生成します。
|
||||
|
||||
また、 ``ExampleFoo`` クラスのテストファイルを作成するために ``bake`` を呼びたい場合は、
|
||||
カスタムコマンド名のクラスサフィックスと名前空間を登録するために ``FooTask`` クラスの
|
||||
``bakeTest()`` メソッドをオーバーライドする必要があります。 ::
|
||||
|
||||
public function bakeTest($className)
|
||||
{
|
||||
if (!isset($this->Test->classSuffixes[$this->name()])) {
|
||||
$this->Test->classSuffixes[$this->name()] = 'Foo';
|
||||
}
|
||||
|
||||
$name = ucfirst($this->name());
|
||||
if (!isset($this->Test->classTypes[$name])) {
|
||||
$this->Test->classTypes[$name] = 'Foo';
|
||||
}
|
||||
|
||||
return parent::bakeTest($className);
|
||||
}
|
||||
|
||||
* **class suffix** は ``bake`` 呼び出しで与えられた名前に追加します。前の例では、
|
||||
``ExampleFooTest.php`` ファイルを作成します。
|
||||
* **class type** は、(あなたが bake するアプリやプラグインに関連する)
|
||||
あなたのファイルを導くために使用されるサブ名前空間です。
|
||||
前の例では、名前空間 ``App\Test\TestCase\Foo`` でテストを作成します。
|
||||
|
||||
.. meta::
|
||||
:title lang=ja: Bake の拡張
|
||||
:keywords lang=ja: command line interface,development,bake view, bake template syntax,twig,erb tags,percent tags
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
Bake コンソール
|
||||
################
|
||||
|
||||
CakePHP の bake コンソールは、迅速に CakePHP を動作させるまでを支援します。
|
||||
bake コンソールは、CakePHP の基本的な素材(モデル、ビヘイビアー、ビュー、ヘルパー、
|
||||
コントローラー、コンポーネント、テストケース、フィクスチャー、プラグイン)を作成できます。
|
||||
その為のスケルトンクラスについては、ここでは省略しますが、
|
||||
bake は数分で完全に機能するアプリケーションを作成できます。
|
||||
要するに、bake は足場の組まれたアプリケーションをいっぺんに手に入れるためにうってつけの方法です。
|
||||
|
||||
インストール手順
|
||||
=================
|
||||
|
||||
bake を使用したり拡張する前に、アプリケーションに bake をインストールしておいてください。
|
||||
bake は Composer を使ってインストールするプラグインとして提供されています。 ::
|
||||
|
||||
composer require --dev cakephp/bake:~1.0
|
||||
|
||||
上記のコマンドは、bake を開発環境で使用するパッケージとしてインストールします。
|
||||
この入れ方の場合、本番環境としてデプロイする際には、 bake はインストールされません。
|
||||
|
||||
Twig テンプレートを使用する場合、 ``WyriHaximus/TwigView`` プラグインをブートストラップとともに
|
||||
読み込んでいることを確認してください。それを完全に省略して、
|
||||
Bake プラグインにこのプラグインを読み込ませることもできます。
|
||||
|
||||
.. meta::
|
||||
:title lang=ja: Bakeコンソール
|
||||
:keywords lang=ja: コマンドライン,CLI,development,bake view, bake template syntax,erb tags,asp tags,percent tags
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
Bake でコード生成
|
||||
##################
|
||||
|
||||
cake コンソールは、 PHP CLI (command line interface) で実行します。
|
||||
もしスクリプトの実行に問題があるなら、以下を満たしてください。
|
||||
|
||||
#. PHP CLI がインストールされているか適切なモジュールが有効か確認してください (例:MySQL, intl)。
|
||||
#. データベースのホストが 'localhost' で問題があるなら、代わりに '127.0.0.1' を使って下さい。
|
||||
PHP CLI でこの問題がおこる可能性があります。
|
||||
#. 使っているコンピューターの設定に応じて、 ``bin/cake bake`` で使用する cake bash スクリプトの
|
||||
実行権限を設定する必要があります。
|
||||
|
||||
bake を実行する前にデータベースとの接続を確認しましょう。
|
||||
|
||||
``bin/cake bake`` を引数無しで実行すると可能なタスクを表示できます。
|
||||
|
||||
Windows システムの場合、 ``bin\cake bake`` を試してみてください。
|
||||
|
||||
それは以下のように表示されます。 ::
|
||||
|
||||
$ bin/cake bake
|
||||
|
||||
Welcome to CakePHP v3.1.6 Console
|
||||
---------------------------------------------------------------
|
||||
App : src
|
||||
Path: /var/www/cakephp.dev/src/
|
||||
PHP: 5.5.8
|
||||
---------------------------------------------------------------
|
||||
The following commands can be used to generate skeleton code for your application.
|
||||
|
||||
Available bake commands:
|
||||
|
||||
- all
|
||||
- behavior
|
||||
- cell
|
||||
- component
|
||||
- controller
|
||||
- fixture
|
||||
- form
|
||||
- helper
|
||||
- mailer
|
||||
- migration
|
||||
- migration_snapshot
|
||||
- model
|
||||
- plugin
|
||||
- shell
|
||||
- shell-helper
|
||||
- template
|
||||
- test
|
||||
|
||||
By using `cake bake [name]` you can invoke a specific bake task.
|
||||
|
||||
より詳しい各コマンドの情報を得るには、 ``--help`` オプションをつけ実行してください。 ::
|
||||
|
||||
$ bin/cake bake controller --help
|
||||
|
||||
Welcome to CakePHP v3.1.6 Console
|
||||
---------------------------------------------------------------
|
||||
App : src
|
||||
Path: /var/www/cakephp.dev/src/
|
||||
---------------------------------------------------------------
|
||||
Bake a controller skeleton.
|
||||
|
||||
Usage:
|
||||
cake bake controller [subcommand] [options] [<name>]
|
||||
|
||||
Subcommands:
|
||||
|
||||
all Bake all controllers with CRUD methods.
|
||||
|
||||
To see help on a subcommand use `cake bake controller [subcommand] --help`
|
||||
|
||||
Options:
|
||||
|
||||
--help, -h Display this help.
|
||||
--verbose, -v Enable verbose output.
|
||||
--quiet, -q Enable quiet output.
|
||||
--plugin, -p Plugin to bake into.
|
||||
--force, -f Force overwriting existing files without prompting.
|
||||
--connection, -c The datasource connection to get data from.
|
||||
(default: default)
|
||||
--theme, -t The theme to use when baking code.
|
||||
--components The comma separated list of components to use.
|
||||
--helpers The comma separated list of helpers to use.
|
||||
--prefix The namespace/routing prefix to use.
|
||||
--no-test Do not generate a test skeleton.
|
||||
--no-actions Do not generate basic CRUD action methods.
|
||||
|
||||
Arguments:
|
||||
|
||||
name Name of the controller to bake. Can use Plugin.name to bake
|
||||
controllers into plugins. (optional)
|
||||
|
||||
Bake テーマオプション
|
||||
=====================
|
||||
|
||||
テーマオプションは全 bake コマンドで一般的です。また、bake テンプレートファイルを変更することができます。
|
||||
テーマを作るには、 :ref:`Bake テーマ作成ドキュメント <creating-a-bake-theme>` をご覧ください。
|
||||
|
||||
.. meta::
|
||||
:title lang=ja: Code Generation with Bake
|
||||
:keywords lang=ja: command line interface,functional application,database,database configuration,bash script,basic ingredients,project,model,path path,code generation,scaffolding,windows users,configuration file,few minutes,config,iew,shell,models,running,mysql
|
||||
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
import sys, os
|
||||
|
||||
# Append the top level directory of the docs, so we can import from the config dir.
|
||||
sys.path.insert(0, os.path.abspath('..'))
|
||||
|
||||
# Pull in all the configuration options defined in the global config file..
|
||||
from config.all import *
|
||||
|
||||
language = 'pt'
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
:caption: CakePHP Bake
|
||||
|
||||
/index
|
||||
/usage
|
||||
/development
|
||||
+280
@@ -0,0 +1,280 @@
|
||||
Extendendo o Bake
|
||||
#################
|
||||
|
||||
Bake fornece uma extenssiva arquitetura que permite a sua aplicação ou plugin ser modificado ou adicionar funcionalidades as bases. Bake faz uso de uma classe view dedicada que usa o `Twig <https://twig.symfony.com/>`_ engine de templates.
|
||||
|
||||
Eventos do Bake
|
||||
===============
|
||||
|
||||
Como uma class view , ``BakeView`` emite o mesmo evento como qualquer outra classe view,
|
||||
mais uma extra que inicializa eventos. No entanto, onde classe view padrão usa o prefixo "View.", ``BakeView`` usa o prefixo "Bake.".
|
||||
|
||||
O inicializador de eventos pode ser usado para fazer mudanças quando aplicadoa toda a saida do bake
|
||||
, por exemplo ao adicionar outro helper ao bake view class este evebti oide ser usado::
|
||||
|
||||
<?php
|
||||
// config/bootstrap_cli.php
|
||||
|
||||
use Cake\Event\Event;
|
||||
use Cake\Event\EventManager;
|
||||
|
||||
EventManager::instance()->on('Bake.initialize', function (Event $event) {
|
||||
$view = $event->getSubject();
|
||||
|
||||
// No meu bake de templates, permite uso de MuSpecial helper
|
||||
$view->loadHelper('MySpecial', ['some' => 'config']);
|
||||
|
||||
// E adicionar uma variável $author então este estará sempre disponível
|
||||
$view->set('author', 'Andy');
|
||||
|
||||
});
|
||||
|
||||
Se você quer modificar o seu bake apartir de outro pugin, coloque o bake do seu plugin dentro do arquivo do seu próprio plugin ``config/bootstrap.php`` será uma boa ideia.
|
||||
|
||||
Os eventos do Bake podem ser úteis para fazer pequenas alterações nos modelos existentes.
|
||||
Por exemplo, para alterar os nomes das variáveis usados quando o controlador / modelo de baking
|
||||
arquivos podem usar uma função ouvindo ``Bake.beforeRender`` para modificar as variaveis usadas no bake templates::
|
||||
|
||||
<?php
|
||||
// config/bootstrap_cli.php
|
||||
|
||||
use Cake\Event\Event;
|
||||
use Cake\Event\EventManager;
|
||||
|
||||
EventManager::instance()->on('Bake.beforeRender', function (Event $event) {
|
||||
$view = $event->getSubject();
|
||||
|
||||
// Use $ rows para a variável de dados principal em índices
|
||||
if ($view->get('pluralName')) {
|
||||
$view->set('pluralName', 'rows');
|
||||
}
|
||||
if ($view->get('pluralVar')) {
|
||||
$view->set('pluralVar', 'rows');
|
||||
}
|
||||
|
||||
// Use $ theOne para a variável de dados principal em exibição / edição
|
||||
if ($view->get('singularName')) {
|
||||
$view->set('singularName', 'theOne');
|
||||
}
|
||||
if ($view->get('singularVar')) {
|
||||
$view->set('singularVar', 'theOne');
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
Você também pode abranger o ``Bake.beforeRender`` e ``Bake.afterRender`` eventos para um arquivo gerado específico. Por exemplo, se você quiser adicionar ações específicas para seu UsersController ao gerar a partir de um arquivo **Controller/controller.twig**,
|
||||
você pode usar o seguinte evento::
|
||||
|
||||
<?php
|
||||
// config/bootstrap_cli.php
|
||||
|
||||
use Cake\Event\Event;
|
||||
use Cake\Event\EventManager;
|
||||
use Cake\Utility\Hash;
|
||||
|
||||
EventManager::instance()->on(
|
||||
'Bake.beforeRender.Controller.controller',
|
||||
function (Event $event) {
|
||||
$view = $event->getSubject();
|
||||
if ($view->viewVars['name'] == 'Users') {
|
||||
// adicionar ações de login e logout ao Users controller
|
||||
$view->viewVars['actions'] = [
|
||||
'login',
|
||||
'logout',
|
||||
'index',
|
||||
'view',
|
||||
'add',
|
||||
'edit',
|
||||
'delete'
|
||||
];
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Ao adicionar eventos que escutam o seu bake de templates, você pode simplesmente relacionar a sua logica de eventos com o bake e fornecer callbacks que são facilmente testáveis.
|
||||
|
||||
Sintaxe de Templates do Bake
|
||||
============================
|
||||
|
||||
Bake arquivos de template usa a sintaxe `Twig <https://twig.symfony.com/doc/2.x/>`__ de templates .
|
||||
|
||||
Uma forma de ver/entender como o bake de templates funciona, especialmente quando tentamos modificar os arquivos de templates, é executar o bake de uma classe que compara o template usado com o template pré processado deixado anteriormente pela aplicação
|
||||
|
||||
**tmp/bake** folder.
|
||||
|
||||
Então, por exemplo, quando baking a shell é como?
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
bin/cake bake shell Foo
|
||||
|
||||
O template usado (**vendor/cakephp/bake/src/Template/Bake/Shell/shell.twig**)
|
||||
parece com algo assim::
|
||||
|
||||
<?php
|
||||
namespace {{ namespace }}\Shell;
|
||||
|
||||
use Cake\Console\Shell;
|
||||
|
||||
/**
|
||||
* {{ name }} shell command.
|
||||
*/
|
||||
class {{ name }}Shell extends Shell
|
||||
{
|
||||
/**
|
||||
* main() method.
|
||||
*
|
||||
* @return bool|int Success or error code.
|
||||
*/
|
||||
public function main()
|
||||
{
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
E o resultado baked é uma classe (**src/Shell/FooShell.php**) que parece algo assim::
|
||||
|
||||
<?php
|
||||
namespace App\Shell;
|
||||
|
||||
use Cake\Console\Shell;
|
||||
|
||||
/**
|
||||
* Foo shell command.
|
||||
*/
|
||||
class FooShell extends Shell
|
||||
{
|
||||
/**
|
||||
* main() method.
|
||||
*
|
||||
* @return bool|int Success or error code.
|
||||
*/
|
||||
public function main()
|
||||
{
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
.. note::
|
||||
|
||||
A priori a versão 1.5.0 bake usava um erb style tag dentro dos arquivos .ctp
|
||||
|
||||
* ``<%`` Um template bake php abre a tag
|
||||
* ``%>`` Um template bake php fecha a tag
|
||||
* ``<%=`` Um template bake php short-echo tag
|
||||
* ``<%-`` Um template bake php abre a tag, revirando qualquer espaço em branco antes da tag
|
||||
* ``-%>`` Um template bake php fecha a tag, revirando qualqualquer espaço em branco após a tag
|
||||
|
||||
.. _creating-a-bake-theme:
|
||||
|
||||
Criando um Tema Bake
|
||||
=====================
|
||||
|
||||
Se você deseja modificar a saída produzida com o comando bake, você pode criar o seu próprio tema para o bake, aos quais permitirá a você subsituir algum ou todos os tempaltes que o bake usa. o mmelhor jeito de fazer isto é:
|
||||
|
||||
#. Bake um novo plugin. O nome do plugin é o bake 'nome do tema'
|
||||
#. Crie uma nova pasta em **plugins/[name]/src/Template/Bake/Template/**.
|
||||
#. Copie qualquer template que você queira para sobrescrer de
|
||||
**vendor/cakephp/bake/src/Template/Bake/Template** que feche com os arquivos no seu plugin.
|
||||
#. Quando executando o bake use a opção ``--theme`` para especificar qual o tema que o bake deve usar
|
||||
. Para evitar problemas com esta opção, em cada chamada, você tambem pode definir o seu template customizado para ser usado como o template padrão::
|
||||
|
||||
<?php
|
||||
// no config/bootstrap.php ou no config/bootstrap_cli.php
|
||||
Configure::write('Bake.theme', 'MyTheme');
|
||||
|
||||
Customizando templates do bake
|
||||
==============================
|
||||
|
||||
Se você deseja modificar a saida produzida pelo comando "bake", você pode
|
||||
criar o seu próprio tema na sua aplicação. Esta forma não usa a opção
|
||||
``--theme`` no na linha de comando quando baking. A melhor forma de fazer isto é:
|
||||
|
||||
#. Criar um novo diretório **/src/Template/Bake/**.
|
||||
#. Copiar qualquer arquivo que você queira sobrescrever de
|
||||
**vendor/cakephp/bake/src/Template/Bake/** para fechar com os arquivos da sua aplicação.
|
||||
|
||||
Criando novos comando bake
|
||||
=================================
|
||||
|
||||
É possivel adicionar novas opções de comandos, ou sobrescrever alguns providos
|
||||
pelo CakePHP, criando tarefas na sua aplicação ou no seu plugin. Extendendo
|
||||
``Bake\Shell\Task\BakeTask``, bake encontrará a nova tarefa e incluirá isto como
|
||||
parte de sí mesmo.
|
||||
|
||||
Como um exemplo, nós vamos criar uma tarefa que cria uma classe foo. Primeiro,
|
||||
crie um arquivo de tarefa **src/Shell/Task/FooTask.php**. Vamos extender de
|
||||
``SimpleBakeTask`` por agora como nossa nova shell task será simples.
|
||||
``SimpleBakeTask`` é abstrata e requer que nós definirmos 3 metodos, que conta
|
||||
ao nosso bake que a tarefa é chamada, onde os arquivos são deverão ser gerados,
|
||||
e o qual template usar. Nosso arquivo FooTask.php deve parecer com ::
|
||||
|
||||
<?php
|
||||
namespace App\Shell\Task;
|
||||
|
||||
use Bake\Shell\Task\SimpleBakeTask;
|
||||
|
||||
class FooTask extends SimpleBakeTask
|
||||
{
|
||||
public $pathFragment = 'Foo/';
|
||||
|
||||
public function name()
|
||||
{
|
||||
return 'foo';
|
||||
}
|
||||
|
||||
public function fileName($name)
|
||||
{
|
||||
return $name . 'Foo.php';
|
||||
}
|
||||
|
||||
public function template()
|
||||
{
|
||||
return 'foo';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Uma vez que o arquivo foi criado, nós precisamos criar um templarte que o bake
|
||||
pdoe usar quando gerar código. Crie **src/Template/Bake/foo.twig**. e neste
|
||||
arquivo nós vamos adicionar o seguinte conteúdo::
|
||||
|
||||
<?php
|
||||
namespace {{ namespace }}\Foo;
|
||||
|
||||
/**
|
||||
* {{ $name }} foo
|
||||
*/
|
||||
class {{ name }}Foo
|
||||
{
|
||||
// Adicione código.
|
||||
}
|
||||
|
||||
Você deve agora poder ver esta nova tarefa na saida de ``bin/cake bake``. Você pode executar a sua nova tarefa executando ``bin/cake bake foo Example``.
|
||||
Isto gerará uma nova classe ``ExampleFoo`` em **src/Foo/ExampleFoo.php**
|
||||
for your application to use.
|
||||
|
||||
Se você quer ``bake`` chame para também criar um arquivo de teste para o sua classe ``ExampleFoo``, você rpecisará sobrescrever o metodo ``bakeTest()`` na classe ``FooTask`` para registrar a classe sufixo e namespace para o seu comando customizado ::
|
||||
|
||||
public function bakeTest($className)
|
||||
{
|
||||
if (!isset($this->Test->classSuffixes[$this->name()])) {
|
||||
$this->Test->classSuffixes[$this->name()] = 'Foo';
|
||||
}
|
||||
|
||||
$name = ucfirst($this->name());
|
||||
if (!isset($this->Test->classTypes[$name])) {
|
||||
$this->Test->classTypes[$name] = 'Foo';
|
||||
}
|
||||
|
||||
return parent::bakeTest($className);
|
||||
}
|
||||
|
||||
* A **class suffix** vai se indexado ao mesmo nome providenciado por você na sua chamada de ``bake``
|
||||
. No exemplo anterior, isto criaria o arquivo ``ExampleFooTest.php`` .
|
||||
* O **class type** vai ser o sub namespace usado para o seu arquivo (relativo ao aplicativo ou plugin que vocês está baking). No exemplo anterior, isto poderia criar o seu teste com o namespace ``App\Test\TestCase\Foo``
|
||||
|
||||
.. meta::
|
||||
:title lang=en: Extending Bake
|
||||
:keywords lang=en: command line interface,development,bake view, bake template syntax,twig,erb tags,percent tags
|
||||
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
Bake Console
|
||||
############
|
||||
|
||||
O bake console do CakePHP é outro empenho para você ter o CakePHP configurado
|
||||
e funcionando rápido. O bake console pode criar qualquer ingrediente básico do
|
||||
CakePHP: models, behaviors, views, helpers, components, test cases, fixtures e
|
||||
plugins. E nós não estamos apenas falando de classes esqueleto: O Bake pode
|
||||
criar uma aplicação totalmente funcional em questão de minutos. De fato, o Bake
|
||||
é um passo natural a se dar uma vez que a aplicação tem seu alicerce construído.
|
||||
|
||||
Instalação
|
||||
==========
|
||||
|
||||
Antes de tentar usar ou extender o bake, tenha certeza que ele está instalado em
|
||||
sua aplicação. O bake é distribuído como um plugin que você pode instalar com o
|
||||
Composer::
|
||||
|
||||
composer require --dev cakephp/bake:~1.0
|
||||
|
||||
Isto irá instalar o bake como uma dependência de desenvolvimento, sendo assim,
|
||||
não instalado quando em um ambiente de produção.
|
||||
|
||||
.. meta::
|
||||
:title lang=pt: Bake Console
|
||||
:keywords lang=pt: cli,linha de comando,command line,dev,desenvolvimento,bake view, bake syntax,erb tags,asp tags,percent tags
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
Geração de código com bake
|
||||
##########################
|
||||
|
||||
O console do cake é executado usando a CLI do PHP (interface da linha de comando).
|
||||
Se você tiver problemas para executar o script, assegure-se de que:
|
||||
|
||||
#. Você instalou a CLI do PHP e possui os módulos apropriados habilitados (por
|
||||
exemplo: MySQL, intl).
|
||||
#. Os usuários também podem ter problemas se o host do banco de dados for
|
||||
'localhost' e deve tentar '127.0.0.1', em vez disso, como localhost pode
|
||||
causar problemas com CLI PHP.
|
||||
#. Dependendo de como o seu computador está configurado, você pode ter que
|
||||
definir direitos de execução no script cake bash para chamá-lo usando
|
||||
``bin/cake bake``.
|
||||
|
||||
Antes de executar o Bake você deve certificar-se de ter pelo menos um banco de dados
|
||||
conexão configurada.
|
||||
|
||||
Quando executado sem argumentos ``bin/cake bake`` irá exibir uma lista de
|
||||
tarefas. Você deve ver algo como::
|
||||
|
||||
$ bin/cake bake
|
||||
|
||||
Welcome to CakePHP v3.4.6 Console
|
||||
---------------------------------------------------------------
|
||||
App : src
|
||||
Path: /var/www/cakephp.dev/src/
|
||||
PHP : 5.6.20
|
||||
---------------------------------------------------------------
|
||||
The following commands can be used to generate skeleton code for your application.
|
||||
|
||||
Available bake commands:
|
||||
|
||||
- all
|
||||
- behavior
|
||||
- cell
|
||||
- component
|
||||
- controller
|
||||
- fixture
|
||||
- form
|
||||
- helper
|
||||
- mailer
|
||||
- migration
|
||||
- migration_diff
|
||||
- migration_snapshot
|
||||
- model
|
||||
- plugin
|
||||
- seed
|
||||
- shell
|
||||
- shell_helper
|
||||
- task
|
||||
- template
|
||||
- test
|
||||
|
||||
By using `cake bake [name]` you can invoke a specific bake task.
|
||||
|
||||
Você pode obter mais informações sobre o que cada tarefa faz e quais são as opções
|
||||
disponível usando o ``--help`` option::
|
||||
|
||||
$ bin/cake bake --help
|
||||
|
||||
Welcome to CakePHP v3.4.6 Console
|
||||
---------------------------------------------------------------
|
||||
App : src
|
||||
Path: /var/www/cakephp.dev/src/
|
||||
PHP : 5.6.20
|
||||
---------------------------------------------------------------
|
||||
The Bake script generates controllers, models and template files for
|
||||
your application. If run with no command line arguments, Bake guides the
|
||||
user through the class creation process. You can customize the
|
||||
generation process by telling Bake where different parts of your
|
||||
application are using command line arguments.
|
||||
|
||||
Usage:
|
||||
cake bake.bake [subcommand] [options]
|
||||
|
||||
Subcommands:
|
||||
|
||||
all Bake a complete MVC skeleton.
|
||||
behavior Bake a behavior class file.
|
||||
cell Bake a cell class file.
|
||||
component Bake a component class file.
|
||||
controller Bake a controller skeleton.
|
||||
fixture Generate fixtures for use with the test suite. You
|
||||
can use `bake fixture all` to bake all fixtures.
|
||||
form Bake a form class file.
|
||||
helper Bake a helper class file.
|
||||
mailer Bake a mailer class file.
|
||||
migration Bake migration class.
|
||||
migration_diff Bake migration class.
|
||||
migration_snapshot Bake migration snapshot class.
|
||||
model Bake table and entity classes.
|
||||
plugin Create the directory structure, AppController class
|
||||
and testing setup for a new plugin. Can create
|
||||
plugins in any of your bootstrapped plugin paths.
|
||||
seed Bake seed class.
|
||||
shell Bake a shell class file.
|
||||
shell_helper Bake a shell_helper class file.
|
||||
task Bake a task class file.
|
||||
template Bake views for a controller, using built-in or
|
||||
custom templates.
|
||||
test Bake test case skeletons for classes.
|
||||
|
||||
To see help on a subcommand use `cake bake.bake [subcommand] --help`
|
||||
|
||||
Options:
|
||||
|
||||
--connection, -c Database connection to use in conjunction with `bake
|
||||
all`. (default: default)
|
||||
--everything Bake a complete MVC skeleton, using all the available
|
||||
tables. Usage: "bake all --everything"
|
||||
--force, -f Force overwriting existing files without prompting.
|
||||
--help, -h Display this help.
|
||||
--plugin, -p Plugin to bake into.
|
||||
--prefix Prefix to bake controllers and templates into.
|
||||
--quiet, -q Enable quiet output.
|
||||
--tablePrefix Table prefix to be used in models.
|
||||
--theme, -t The theme to use when baking code. (choices:
|
||||
Bake|Migrations)
|
||||
--verbose, -v Enable verbose output.
|
||||
|
||||
Temas para o Bake
|
||||
=================
|
||||
|
||||
A opção de tema é comum a todos os comandos do bake, e permite mudar os arquivos de modelo usados no bake. Para criar seus próprios modelos, veja a
|
||||
:ref:`documentação de criação de themes para o bake <creating-a-bake-theme>`.
|
||||
|
||||
.. meta::
|
||||
:title lang=pt: Geração de código com bake
|
||||
:keywords lang=pt: command line interface,functional application,database,database configuration,bash script,basic ingredients,project,model,path path,code generation,scaffolding,windows users,configuration file,few minutes,config,iew,shell,models,running,mysql
|
||||
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
import sys, os
|
||||
|
||||
# Append the top level directory of the docs, so we can import from the config dir.
|
||||
sys.path.insert(0, os.path.abspath('..'))
|
||||
|
||||
# Pull in all the configuration options defined in the global config file..
|
||||
from config.all import *
|
||||
|
||||
language = 'ru'
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
:caption: CakePHP Bake
|
||||
|
||||
/index
|
||||
/usage
|
||||
/development
|
||||
+293
@@ -0,0 +1,293 @@
|
||||
Расширение возможностей Bake
|
||||
############################
|
||||
|
||||
Bake имеет расширяемую архитектуру, которая позволяет вашему приложению или плагинам
|
||||
измененять или добавления его базовую функциональность. Bake использует специальный
|
||||
класс, который использует механизм шаблонизатора `Twig <https://twig.symfony.com/>`_.
|
||||
|
||||
События Bake
|
||||
============
|
||||
|
||||
В качестве класса представления ``BakeView`` генерирует те же события, что и любой другой класс представления,
|
||||
плюс одно дополнительное событие инициализации. Однако, в то время как классы стандартного представления используют
|
||||
префикс события "View.", ``BakeView`` использует префикс события "Bake.".
|
||||
|
||||
Событие initialize можно использовать для внесения изменений, которые применяются ко всем 'испеченным'
|
||||
выводам, например, чтобы добавить другого помощника в класс вида bake, это событие может
|
||||
использовать следующее::
|
||||
|
||||
<?php
|
||||
// config/bootstrap_cli.php
|
||||
|
||||
use Cake\Event\Event;
|
||||
use Cake\Event\EventManager;
|
||||
|
||||
EventManager::instance()->on('Bake.initialize', function (Event $event) {
|
||||
$view = $event->getSubject();
|
||||
|
||||
// В моих шаблонах bake, разрешить использование MySpecial helper
|
||||
$view->loadHelper('MySpecial', ['some' => 'config']);
|
||||
|
||||
// И добавьте переменную $author, чтобы она всегда была доступна
|
||||
$view->set('author', 'Andy');
|
||||
|
||||
});
|
||||
|
||||
Если вы хотите изменить выпечку из другого плагина, хорошей идеей будет - поместить
|
||||
события своего плагина в файл ``config/bootstrap.php``.
|
||||
|
||||
События Bake могут быть полезны для внесения небольших изменений в существующие шаблоны.
|
||||
Например, чтобы изменить имена переменных, используемых для выпечки файлов контроллеров/шаблонов,
|
||||
можно использовать прослушивающую функцию ``Bake.beforeRender``::
|
||||
|
||||
<?php
|
||||
// config/bootstrap_cli.php
|
||||
|
||||
use Cake\Event\Event;
|
||||
use Cake\Event\EventManager;
|
||||
|
||||
EventManager::instance()->on('Bake.beforeRender', function (Event $event) {
|
||||
$view = $event->getSubject();
|
||||
|
||||
// Использовать $rows для основной переменной данных для индекса (index)
|
||||
if ($view->get('pluralName')) {
|
||||
$view->set('pluralName', 'rows');
|
||||
}
|
||||
if ($view->get('pluralVar')) {
|
||||
$view->set('pluralVar', 'rows');
|
||||
}
|
||||
|
||||
// Используйте $theOne для основной переменной данных для просмотра/редактирования (view/edit)
|
||||
if ($view->get('singularName')) {
|
||||
$view->set('singularName', 'theOne');
|
||||
}
|
||||
if ($view->get('singularVar')) {
|
||||
$view->set('singularVar', 'theOne');
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
Вы также можете использовать события ``Bake.beforeRender`` и ``Bake.afterRender`` для
|
||||
генерирования специфичного файла. Например, если вы хотите добавить определенные действия для
|
||||
вашего UserController при генерации из файла **Controller/controller.twig**,
|
||||
вы можете использовать следующее событие::
|
||||
|
||||
<?php
|
||||
// config/bootstrap_cli.php
|
||||
|
||||
use Cake\Event\Event;
|
||||
use Cake\Event\EventManager;
|
||||
use Cake\Utility\Hash;
|
||||
|
||||
EventManager::instance()->on(
|
||||
'Bake.beforeRender.Controller.controller',
|
||||
function (Event $event) {
|
||||
$view = $event->getSubject();
|
||||
if ($view->viewVars['name'] == 'Users') {
|
||||
// добавим действия входа и выхода из системы в контроллер пользователей
|
||||
$view->viewVars['actions'] = [
|
||||
'login',
|
||||
'logout',
|
||||
'index',
|
||||
'view',
|
||||
'add',
|
||||
'edit',
|
||||
'delete'
|
||||
];
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
При просмотре прослушивателей событий для конкретных шаблонов выпечки вы можете упростить
|
||||
выпечку связанной логики событий и обеспечить обратные вызовы, которые легче тестировать.
|
||||
|
||||
Синтаксис шаблона выпечки
|
||||
=========================
|
||||
|
||||
Файлы шаблонов Bake используют синтаксис шаблонизатора `Twig <https://twig.symfony.com/doc/2.x/>`__.
|
||||
|
||||
Один из способов увидеть/понять, как работают шаблоны выпечки, особенно при попытке
|
||||
изменить файлы шаблонов выпечки, это - испечь класс и сравнить используемый шаблон
|
||||
с предварительно обработанным файлом шаблона, который остаётся в приложении в папке
|
||||
**tmp/bake**.
|
||||
|
||||
Так, например, при выпечке такой оболочки:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
bin/cake bake shell Foo
|
||||
|
||||
Используемый шаблон (**vendor/cakephp/bake/src/Template/Bake/Shell/shell.twig**)
|
||||
будет выглядеть так::
|
||||
|
||||
<?php
|
||||
namespace {{ namespace }}\Shell;
|
||||
|
||||
use Cake\Console\Shell;
|
||||
|
||||
/**
|
||||
* {{ name }} shell command.
|
||||
*/
|
||||
class {{ name }}Shell extends Shell
|
||||
{
|
||||
/**
|
||||
* main() method.
|
||||
*
|
||||
* @return bool|int Success or error code.
|
||||
*/
|
||||
public function main()
|
||||
{
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
И итоговый испеченный класс (**src/Shell/FooShell.php**) будет выглядеть так::
|
||||
|
||||
<?php
|
||||
namespace App\Shell;
|
||||
|
||||
use Cake\Console\Shell;
|
||||
|
||||
/**
|
||||
* Foo shell command.
|
||||
*/
|
||||
class FooShell extends Shell
|
||||
{
|
||||
/**
|
||||
* main() method.
|
||||
*
|
||||
* @return bool|int Success or error code.
|
||||
*/
|
||||
public function main()
|
||||
{
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
.. note::
|
||||
|
||||
До версии 1.5.0 bake использовал пользовательские теги erb-стиля внутри файлов шаблонов .ctp
|
||||
|
||||
* ``<%`` Bake шаблон открывающего тега php
|
||||
* ``%>`` Bake шаблон закрывающего тега php
|
||||
* ``<%=`` Bake шаблон php короткого php тега echo
|
||||
* ``<%-`` Bake шаблон php открытия тега, удаляющего любые введённые пробелы перед тегом
|
||||
* ``-%>`` Bake шаблон php закрытия тега, любые введённые пробелы после тега
|
||||
|
||||
.. _creating-a-bake-theme:
|
||||
|
||||
Создание темы Bake
|
||||
==================
|
||||
|
||||
Если вы хотите изменить результат, полученный командой "bake", вы можете
|
||||
создать свою собственную тему('theme') для "bake", которая позволит вам заменить некоторые или все
|
||||
шаблоны, которые испекает bake. Лучше всего сделать это так:
|
||||
|
||||
#. Выпечь новый плагин. Имя плагина - это название темы 'bake'
|
||||
#. Создать новую диреткорию **plugins/[name]/src/Template/Bake/Template/**.
|
||||
#. Скопируйте любые шаблоны, которые вы хотите переопределить
|
||||
**vendor/cakephp/bake/src/Template/Bake/Template** для сопоставления файлов с вашим плагином.
|
||||
#. При запуске выпечки используйте параметр ``--theme``, чтобы указать тему выпечки которую вы
|
||||
хотите использовать. Чтобы избежать необходимости указывать этот параметр в каждом вызове, вы также можете
|
||||
настроить свою тему в качестве темы по умолчанию::
|
||||
|
||||
<?php
|
||||
// В config/bootstrap.php или config/bootstrap_cli.php
|
||||
Configure::write('Bake.theme', 'MyTheme');
|
||||
|
||||
Настройка шаблонов Bake
|
||||
=======================
|
||||
|
||||
Если вы хотите изменить вывод по умолчанию, созданный командой "bake", вы можете
|
||||
создать свои собственные шаблоны выпечки в своём приложении. Этот способ не использует
|
||||
``--theme`` в командной строке при выпечке. Лучше всего сделать это так:
|
||||
|
||||
#. Создайте новую директорию(папку) **/src/Template/Bake/**.
|
||||
#. Скопируйте шаблоны которые вы хотите изменить в вашем приложении в
|
||||
**vendor/cakephp/bake/src/Template/Bake/**.
|
||||
|
||||
Создание новых параметров команды Bake
|
||||
======================================
|
||||
|
||||
Можно добавить новые параметры команды bake или переопределить те, которые предоставлены
|
||||
CakePHP, создавая задачи в своём приложении или плагинах. Расширение
|
||||
``Bake\Shell\Task\BakeTask`` найдёт вашу новую задачу и включит ее как часть выпечки.
|
||||
|
||||
В качестве примера мы создадим задачу, которая создает произвольный класс foo. Первым делом,
|
||||
создайте сам файл задачи **src/Shell/Task/FooTask.php**. Мы расширим
|
||||
``SimpleBakeTask``, поскольку наша задача для оболочки будет простой. ``SimpleBakeTask``
|
||||
является абстрактным и требует, чтобы мы определили 3 метода, которые подсказывают ему, какова задача
|
||||
которую должен генерировать файл, и какой шаблон при этом использовать. Наш файл FooTask.php должен выглядеть так::
|
||||
|
||||
<?php
|
||||
namespace App\Shell\Task;
|
||||
|
||||
use Bake\Shell\Task\SimpleBakeTask;
|
||||
|
||||
class FooTask extends SimpleBakeTask
|
||||
{
|
||||
public $pathFragment = 'Foo/';
|
||||
|
||||
public function name()
|
||||
{
|
||||
return 'foo';
|
||||
}
|
||||
|
||||
public function fileName($name)
|
||||
{
|
||||
return $name . 'Foo.php';
|
||||
}
|
||||
|
||||
public function template()
|
||||
{
|
||||
return 'foo';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Как только этот файл будет создан, нам нужно создать шаблон, который bake может использовать
|
||||
для генерации кода. Создайте файл **src/Template/Bake/foo.twig**. В этом файле добавим
|
||||
следующее содержание::
|
||||
|
||||
<?php
|
||||
namespace {{ namespace }}\Foo;
|
||||
|
||||
/**
|
||||
* {{ $name }} foo
|
||||
*/
|
||||
class {{ name }}Foo
|
||||
{
|
||||
// Добавить код.
|
||||
}
|
||||
|
||||
Теперь вы должны увидеть свою новую задачу в выводе ``bin/cake bake``. Теперь можете
|
||||
запустить новую задачу, прописав в командной строке: ``bin/cake bake foo Example``.
|
||||
Это создаст новый класс ``ExampleFoo`` в **src/Foo/ExampleFoo.php** для вашего приложения.
|
||||
|
||||
Если вы хотите, чтобы вызов ``bake`` ищё и создавал тестовый файл для вашего
|
||||
``ExampleFoo``, вам нужно перезаписать метод ``bakeTest()`` в
|
||||
``FooTask`` для регистрации команды суффикса класса и пространства имен для вашего
|
||||
пользовательского интерфейса::
|
||||
|
||||
public function bakeTest($className)
|
||||
{
|
||||
if (!isset($this->Test->classSuffixes[$this->name()])) {
|
||||
$this->Test->classSuffixes[$this->name()] = 'Foo';
|
||||
}
|
||||
|
||||
$name = ucfirst($this->name());
|
||||
if (!isset($this->Test->classTypes[$name])) {
|
||||
$this->Test->classTypes[$name] = 'Foo';
|
||||
}
|
||||
|
||||
return parent::bakeTest($className);
|
||||
}
|
||||
|
||||
* **Суффикс класса** будет добавлен к имени, указанному в вашем вызове ``bake``.
|
||||
В предыдущем примере он создал бы файл ``ExampleFooTest.php``.
|
||||
|
||||
* **Тип файла** будет использовать пространство под-пространство имён(sub-namespace), которое приведёт к файлу (относительно приложения или подключаемого модуля). В предыдущем примере, он создаст ваш тест с пространством имен ``App\Test\TestCase\Foo``.
|
||||
|
||||
.. meta::
|
||||
:title lang=ru: Расширение возможностей Bake
|
||||
:keywords lang=ru: интерфейс командной строки, разработка, выпечка, синтаксис шаблона выпечки, твинг, метки erb, процентные теги
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
Консоль Bake
|
||||
############
|
||||
|
||||
Bake консоль CakePHP - это еще один инструмент для быстрой разработки на фреймворке CakePHP.
|
||||
Консоль Bake может создать любой из базовых компонентов или все сразу: models,
|
||||
behaviors, views, helpers, controllers, components, test cases, fixtures и plugins.
|
||||
Речь идет не только о каркасе приложения: Bake консоль создает полностью функционирующее приложение всего за пару минут.
|
||||
|
||||
Bake это естественный шаг для статической генерации кода.
|
||||
|
||||
Установка
|
||||
=========
|
||||
|
||||
Перед тем, как использовать Bake, убедитесь, что он установлен в вашем приложении.
|
||||
Bake это отдельный плагин и вы можете установить его с помощью Composer::
|
||||
|
||||
composer require --dev cakephp/bake:~1.0
|
||||
|
||||
Команда выше установит Bake в зависимости от разработки.
|
||||
Это значит, что Bake не будет установлен, когда вы делаете деплой на продакшн сервер.
|
||||
|
||||
.. meta::
|
||||
:title lang=ru: Консоль Bake
|
||||
:keywords lang=ru: интерфейс командной строки,разработка,bake view, bake template syntax,erb tags,asp tags,percent tags
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
Генерация кода с помощью Bake
|
||||
#############################
|
||||
|
||||
Консоль cake запускается с использованием PHP CLI (интерфейса командной строки).
|
||||
Если у вас возникли проблемы с запуском скрипта, убедитесь, что:
|
||||
|
||||
#. У вас установлен PHP CLI и что у него есть соответствующие включённые модули
|
||||
(например: MySQL, intl).
|
||||
#. У пользователей также могут быть проблемы, если хост базы данных является
|
||||
'localhost' вмеcто этого можно попробовать '127.0.0.1', поскольку localhost
|
||||
может вызвать проблемы с PHP CLI.
|
||||
#. В зависимости от того, как настроен ваш компьютер, вам может потребоваться
|
||||
установить права выполнения на скрипт bash, чтобы вызвать его, используя
|
||||
``bin/cake bake``.
|
||||
|
||||
Перед запуском bake вы должны убедиться, что у вас есть хотя бы одна база данных и
|
||||
соединение настроено.
|
||||
|
||||
При запуске без аргументов ``bin/cake bake`` выводит список доступных
|
||||
заданий. Вы должны увидеть что-то вроде::
|
||||
|
||||
$ bin/cake bake
|
||||
|
||||
Welcome to CakePHP v3.4.6 Console
|
||||
---------------------------------------------------------------
|
||||
App : src
|
||||
Path: /var/www/cakephp.dev/src/
|
||||
PHP : 5.6.20
|
||||
---------------------------------------------------------------
|
||||
The following commands can be used to generate skeleton code for your application.
|
||||
|
||||
Available bake commands:
|
||||
|
||||
- all
|
||||
- behavior
|
||||
- cell
|
||||
- component
|
||||
- controller
|
||||
- fixture
|
||||
- form
|
||||
- helper
|
||||
- mailer
|
||||
- migration
|
||||
- migration_diff
|
||||
- migration_snapshot
|
||||
- model
|
||||
- plugin
|
||||
- seed
|
||||
- shell
|
||||
- shell_helper
|
||||
- task
|
||||
- template
|
||||
- test
|
||||
|
||||
By using `cake bake [name]` you can invoke a specific bake task.
|
||||
|
||||
Вы можете получить больше дополнительной информации о том, что делает каждая задача, и какие параметры
|
||||
доступны, если используете ключ ``--help``::
|
||||
|
||||
$ bin/cake bake --help
|
||||
|
||||
Welcome to CakePHP v3.4.6 Console
|
||||
---------------------------------------------------------------
|
||||
App : src
|
||||
Path: /var/www/cakephp.dev/src/
|
||||
PHP : 5.6.20
|
||||
---------------------------------------------------------------
|
||||
The Bake script generates controllers, models and template files for
|
||||
your application. If run with no command line arguments, Bake guides the
|
||||
user through the class creation process. You can customize the
|
||||
generation process by telling Bake where different parts of your
|
||||
application are using command line arguments.
|
||||
|
||||
Usage:
|
||||
cake bake.bake [subcommand] [options]
|
||||
|
||||
Subcommands:
|
||||
|
||||
all Bake a complete MVC skeleton.
|
||||
behavior Bake a behavior class file.
|
||||
cell Bake a cell class file.
|
||||
component Bake a component class file.
|
||||
controller Bake a controller skeleton.
|
||||
fixture Generate fixtures for use with the test suite. You
|
||||
can use `bake fixture all` to bake all fixtures.
|
||||
form Bake a form class file.
|
||||
helper Bake a helper class file.
|
||||
mailer Bake a mailer class file.
|
||||
migration Bake migration class.
|
||||
migration_diff Bake migration class.
|
||||
migration_snapshot Bake migration snapshot class.
|
||||
model Bake table and entity classes.
|
||||
plugin Create the directory structure, AppController class
|
||||
and testing setup for a new plugin. Can create
|
||||
plugins in any of your bootstrapped plugin paths.
|
||||
seed Bake seed class.
|
||||
shell Bake a shell class file.
|
||||
shell_helper Bake a shell_helper class file.
|
||||
task Bake a task class file.
|
||||
template Bake views for a controller, using built-in or
|
||||
custom templates.
|
||||
test Bake test case skeletons for classes.
|
||||
|
||||
To see help on a subcommand use `cake bake.bake [subcommand] --help`
|
||||
|
||||
Options:
|
||||
|
||||
--connection, -c Database connection to use in conjunction with `bake
|
||||
all`. (default: default)
|
||||
--everything Bake a complete MVC skeleton, using all the available
|
||||
tables. Usage: "bake all --everything"
|
||||
--force, -f Force overwriting existing files without prompting.
|
||||
--help, -h Display this help.
|
||||
--plugin, -p Plugin to bake into.
|
||||
--prefix Prefix to bake controllers and templates into.
|
||||
--quiet, -q Enable quiet output.
|
||||
--tablePrefix Table prefix to be used in models.
|
||||
--theme, -t The theme to use when baking code. (choices:
|
||||
Bake|Migrations)
|
||||
--verbose, -v Enable verbose output.
|
||||
|
||||
Темы Bake
|
||||
=========
|
||||
|
||||
Параметр темы является общим для всех команд bake, так же bake позволяет изменять
|
||||
файлы шаблонов, используемые при 'выпечке'. Чтобы создать свои собственные шаблоны см.
|
||||
:ref:`документация по созданию темы<creating-a-bake-theme>`.
|
||||
|
||||
.. meta::
|
||||
:title lang=ru: Генерация кода с помощью Bake
|
||||
:keywords lang=en: command line interface,functional application,database,database configuration,bash script,basic ingredients,project,model,path path,code generation,scaffolding,windows users,configuration file,few minutes,config,iew,shell,models,running,mysql
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0"?>
|
||||
<ruleset name="CakePHP Core">
|
||||
<rule ref="./vendor/cakephp/cakephp-codesniffer/CakePHP/ruleset.xml">
|
||||
<!-- Exclude unwanted sniffs -->
|
||||
</rule>
|
||||
|
||||
<!-- Necessary for class aliases used for backwards compat -->
|
||||
<rule ref="PSR1.Files.SideEffects.FoundWithSymbols">
|
||||
<severity>0</severity>
|
||||
</rule>
|
||||
</ruleset>
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
parameters:
|
||||
level: 5
|
||||
autoload_files:
|
||||
- tests/bootstrap.php
|
||||
ignoreErrors:
|
||||
- '#Call to an undefined method Cake\\Database\\Type::getDateTimeClassName\(\)#'
|
||||
- '#Parameter \#1 \$size of method .+CollectionInterface::take\(\) expects int, array given.#'
|
||||
Vendored
+52
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 1.7.2
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Bake;
|
||||
|
||||
use Cake\Core\BasePlugin;
|
||||
use Cake\Core\PluginApplicationInterface;
|
||||
|
||||
/**
|
||||
* Plugin class for bake
|
||||
*/
|
||||
class Plugin extends BasePlugin
|
||||
{
|
||||
/**
|
||||
* Plugin name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $name = 'Bake';
|
||||
|
||||
/**
|
||||
* Override to do nothing.
|
||||
*
|
||||
* @param \Cake\Routing\RouteBuilder $routes The route builder to update.
|
||||
* @return void
|
||||
*/
|
||||
public function routes($routes)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* load WyriHaximus/TwigView plugin.
|
||||
*
|
||||
* @param \Cake\Core\PluginApplicationInterface $app The host application
|
||||
* @return void
|
||||
*/
|
||||
public function bootstrap(PluginApplicationInterface $app)
|
||||
{
|
||||
$app->addPlugin('WyriHaximus/TwigView');
|
||||
}
|
||||
}
|
||||
+332
@@ -0,0 +1,332 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.1.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Bake\Shell;
|
||||
|
||||
use Bake\Utility\CommonOptionsTrait;
|
||||
use Cake\Cache\Cache;
|
||||
use Cake\Console\Shell;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Core\ConventionsTrait;
|
||||
use Cake\Core\Plugin;
|
||||
use Cake\Datasource\ConnectionManager;
|
||||
use Cake\Utility\Inflector;
|
||||
|
||||
/**
|
||||
* Command-line code generation utility to automate programmer chores.
|
||||
*
|
||||
* Bake is CakePHP's code generation script, which can help you kickstart
|
||||
* application development by writing fully functional skeleton controllers,
|
||||
* models, and templates. Going further, Bake can also write Unit Tests for you.
|
||||
*
|
||||
* @link https://book.cakephp.org/3.0/en/bake/usage.html
|
||||
*
|
||||
* @property \Bake\Shell\Task\ModelTask $Model
|
||||
*/
|
||||
class BakeShell extends Shell
|
||||
{
|
||||
use CommonOptionsTrait;
|
||||
use ConventionsTrait;
|
||||
|
||||
/**
|
||||
* The connection being used.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $connection = 'default';
|
||||
|
||||
/**
|
||||
* Assign $this->connection to the active task if a connection param is set.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function startup()
|
||||
{
|
||||
parent::startup();
|
||||
Configure::write('debug', true);
|
||||
Cache::disable();
|
||||
// Loading WyriHaximus/TwigView Plugin through the Plugin::load() for backward compatibility.
|
||||
if (!Plugin::isLoaded('WyriHaximus/TwigView')) {
|
||||
Plugin::load('WyriHaximus/TwigView', ['bootstrap' => true]);
|
||||
}
|
||||
|
||||
$task = $this->_camelize($this->command);
|
||||
|
||||
if (isset($this->{$task}) && !in_array($task, ['Project'])) {
|
||||
if (isset($this->params['connection'])) {
|
||||
$this->{$task}->connection = $this->params['connection'];
|
||||
}
|
||||
if (isset($this->params['tablePrefix'])) {
|
||||
$this->{$task}->tablePrefix = $this->params['tablePrefix'];
|
||||
}
|
||||
}
|
||||
if (isset($this->params['connection'])) {
|
||||
$this->connection = $this->params['connection'];
|
||||
}
|
||||
|
||||
if ($this->params['quiet']) {
|
||||
$this->interactive = false;
|
||||
if (isset($this->{$task}) && !in_array($task, ['Project'])) {
|
||||
$this->{$task}->interactive = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Override main() to handle action
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function main()
|
||||
{
|
||||
if ($this->args && $this->args[0] === 'view') {
|
||||
$this->out('<error>The view command has been renamed.</error>');
|
||||
$this->out('To create template files, please use the template command:', 2);
|
||||
$args = $this->args;
|
||||
array_shift($args);
|
||||
$args = implode($args, ' ');
|
||||
$this->out(sprintf(' <info>`bin/cake bake template %s`</info>', $args), 2);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$connections = ConnectionManager::configured();
|
||||
if (empty($connections)) {
|
||||
$this->out('Your database configuration was not found.');
|
||||
$this->out('Add your database connection information to config/app.php.');
|
||||
|
||||
return false;
|
||||
}
|
||||
$this->out('The following commands can be used to generate skeleton code for your application.', 2);
|
||||
$this->out('<info>Available bake commands:</info>', 2);
|
||||
$this->out('- all');
|
||||
$names = [];
|
||||
foreach ($this->tasks as $task) {
|
||||
list(, $name) = pluginSplit($task);
|
||||
$names[] = Inflector::underscore($name);
|
||||
}
|
||||
sort($names);
|
||||
foreach ($names as $name) {
|
||||
$this->out('- ' . $name);
|
||||
}
|
||||
$this->out('');
|
||||
$this->out('By using <info>`cake bake [name]`</info> you can invoke a specific bake task.');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Locate the tasks bake will use.
|
||||
*
|
||||
* Scans the following paths for tasks that are subclasses of
|
||||
* Cake\Shell\Task\BakeTask:
|
||||
*
|
||||
* - Cake/Shell/Task/
|
||||
* - Shell/Task for each loaded plugin
|
||||
* - App/Shell/Task/
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function loadTasks()
|
||||
{
|
||||
$tasks = [];
|
||||
|
||||
foreach (Plugin::loaded() as $plugin) {
|
||||
$tasks = $this->_findTasks(
|
||||
$tasks,
|
||||
Plugin::classPath($plugin),
|
||||
str_replace('/', '\\', $plugin),
|
||||
$plugin
|
||||
);
|
||||
}
|
||||
$tasks = $this->_findTasks($tasks, APP, Configure::read('App.namespace'));
|
||||
|
||||
$this->tasks = array_values($tasks);
|
||||
|
||||
return parent::loadTasks();
|
||||
}
|
||||
|
||||
/**
|
||||
* Append matching tasks in $path to the $tasks array.
|
||||
*
|
||||
* @param array $tasks The task list to modify and return.
|
||||
* @param string $path The base path to look in.
|
||||
* @param string $namespace The base namespace.
|
||||
* @param string|null $prefix The prefix to append.
|
||||
* @return array Updated tasks.
|
||||
*/
|
||||
protected function _findTasks($tasks, $path, $namespace, $prefix = null)
|
||||
{
|
||||
$path .= 'Shell/Task';
|
||||
if (!is_dir($path)) {
|
||||
return $tasks;
|
||||
}
|
||||
$candidates = $this->_findClassFiles($path, $namespace);
|
||||
$classes = $this->_findTaskClasses($candidates);
|
||||
foreach ($classes as $class) {
|
||||
list(, $name) = namespaceSplit($class);
|
||||
$name = substr($name, 0, -4);
|
||||
$fullName = ($prefix ? $prefix . '.' : '') . $name;
|
||||
$tasks[$name] = $fullName;
|
||||
}
|
||||
|
||||
return $tasks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find task classes in a given path.
|
||||
*
|
||||
* @param string $path The path to scan.
|
||||
* @param string $namespace Namespace.
|
||||
* @return array An array of files that may contain bake tasks.
|
||||
*/
|
||||
protected function _findClassFiles($path, $namespace)
|
||||
{
|
||||
$iterator = new \DirectoryIterator($path);
|
||||
$candidates = [];
|
||||
foreach ($iterator as $item) {
|
||||
if ($item->isDot() || $item->isDir()) {
|
||||
continue;
|
||||
}
|
||||
$name = $item->getBasename('.php');
|
||||
$candidates[] = $namespace . '\Shell\Task\\' . $name;
|
||||
}
|
||||
|
||||
return $candidates;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find bake tasks in a given set of files.
|
||||
*
|
||||
* @param array $files The array of files.
|
||||
* @return array An array of matching classes.
|
||||
*/
|
||||
protected function _findTaskClasses($files)
|
||||
{
|
||||
$classes = [];
|
||||
foreach ($files as $className) {
|
||||
if (!class_exists($className)) {
|
||||
continue;
|
||||
}
|
||||
$reflect = new \ReflectionClass($className);
|
||||
if (!$reflect->isInstantiable()) {
|
||||
continue;
|
||||
}
|
||||
if (!$reflect->isSubclassOf('Bake\Shell\Task\BakeTask')) {
|
||||
continue;
|
||||
}
|
||||
$classes[] = $className;
|
||||
}
|
||||
|
||||
return $classes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Quickly bake the MVC
|
||||
*
|
||||
* @param string|null $name Name.
|
||||
* @return bool
|
||||
*/
|
||||
public function all($name = null)
|
||||
{
|
||||
if (
|
||||
$this->param('connection') && $this->param('everything') &&
|
||||
$this->param('connection') !== 'default'
|
||||
) {
|
||||
$this->warn('Can only bake everything on default connection');
|
||||
|
||||
return false;
|
||||
}
|
||||
$this->out('Bake All');
|
||||
$this->hr();
|
||||
|
||||
if (!empty($this->params['connection'])) {
|
||||
$this->connection = $this->params['connection'];
|
||||
}
|
||||
|
||||
if (empty($name) && !$this->param('everything')) {
|
||||
$this->Model->connection = $this->connection;
|
||||
$this->out('Possible model names based on your database:');
|
||||
foreach ($this->Model->listUnskipped() as $table) {
|
||||
$this->out('- ' . $table);
|
||||
}
|
||||
$this->out('Run <info>`cake bake all [name]`</info> to generate skeleton files.');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$allTables = collection([$name]);
|
||||
$filteredTables = $allTables;
|
||||
|
||||
if ($this->param('everything')) {
|
||||
$this->Model->connection = $this->connection;
|
||||
$filteredTables = collection($this->Model->listUnskipped());
|
||||
}
|
||||
|
||||
foreach (['Model', 'Controller', 'Template'] as $task) {
|
||||
$filteredTables->each(function ($tableName) use ($task) {
|
||||
$tableName = $this->_camelize($tableName);
|
||||
$this->{$task}->connection = $this->connection;
|
||||
$this->{$task}->interactive = $this->interactive;
|
||||
$this->{$task}->main($tableName);
|
||||
});
|
||||
}
|
||||
|
||||
$this->out('<success>Bake All complete.</success>', 1, Shell::QUIET);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the option parser instance and configures it.
|
||||
*
|
||||
* @return \Cake\Console\ConsoleOptionParser
|
||||
*/
|
||||
public function getOptionParser()
|
||||
{
|
||||
$parser = parent::getOptionParser();
|
||||
|
||||
$parser->setDescription(
|
||||
'The Bake script generates controllers, models and template files for your application.' .
|
||||
' If run with no command line arguments, Bake guides the user through the class creation process.' .
|
||||
' You can customize the generation process by telling Bake where different parts of your application' .
|
||||
' are using command line arguments.'
|
||||
)->addSubcommand('all', [
|
||||
'help' => 'Bake a complete MVC skeleton.',
|
||||
])->addOption('everything', [
|
||||
'help' => 'Bake a complete MVC skeleton, using all the available tables. ' .
|
||||
'Usage: "bake all --everything"',
|
||||
'default' => false,
|
||||
'boolean' => true,
|
||||
])->addOption('prefix', [
|
||||
'help' => 'Prefix to bake controllers and templates into.',
|
||||
])->addOption('tablePrefix', [
|
||||
'help' => 'Table prefix to be used in models.',
|
||||
'default' => null,
|
||||
]);
|
||||
|
||||
$parser = $this->_setCommonOptions($parser);
|
||||
|
||||
foreach ($this->_taskMap as $task => $config) {
|
||||
$taskParser = $this->{$task}->getOptionParser();
|
||||
$this->{$task}->interactive = $this->interactive;
|
||||
$parser->addSubcommand(Inflector::underscore($task), [
|
||||
'help' => $taskParser->getDescription(),
|
||||
'parser' => $taskParser,
|
||||
]);
|
||||
}
|
||||
|
||||
return $parser;
|
||||
}
|
||||
}
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.1.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Bake\Shell\Task;
|
||||
|
||||
use Bake\Utility\CommonOptionsTrait;
|
||||
use Cake\Cache\Cache;
|
||||
use Cake\Console\Shell;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Core\ConventionsTrait;
|
||||
use Cake\Filesystem\File;
|
||||
|
||||
/**
|
||||
* Base class for Bake Tasks.
|
||||
*/
|
||||
class BakeTask extends Shell
|
||||
{
|
||||
use CommonOptionsTrait;
|
||||
use ConventionsTrait;
|
||||
|
||||
/**
|
||||
* Table prefix
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
public $tablePrefix = null;
|
||||
|
||||
/**
|
||||
* The pathFragment appended to the plugin/app path.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $pathFragment;
|
||||
|
||||
/**
|
||||
* Name of plugin
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $plugin = null;
|
||||
|
||||
/**
|
||||
* The db connection being used for baking
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $connection = null;
|
||||
|
||||
/**
|
||||
* Disable caching and enable debug for baking.
|
||||
* This forces the most current database schema to be used.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function startup()
|
||||
{
|
||||
Configure::write('debug', true);
|
||||
Cache::disable();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize hook.
|
||||
*
|
||||
* Populates the connection property, which is useful for tasks of tasks.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function initialize()
|
||||
{
|
||||
if (empty($this->connection) && !empty($this->params['connection'])) {
|
||||
$this->connection = $this->params['connection'];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the prefix name.
|
||||
*
|
||||
* Handles camelcasing each namespace in the prefix path.
|
||||
*
|
||||
* @return string The inflected prefix path.
|
||||
*/
|
||||
protected function _getPrefix()
|
||||
{
|
||||
$prefix = $this->param('prefix');
|
||||
if (!$prefix) {
|
||||
return '';
|
||||
}
|
||||
$parts = explode('/', $prefix);
|
||||
|
||||
return implode('/', array_map([$this, '_camelize'], $parts));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the path for output. Checks the plugin property
|
||||
* and returns the correct path.
|
||||
*
|
||||
* @return string Path to output.
|
||||
*/
|
||||
public function getPath()
|
||||
{
|
||||
$path = APP . $this->pathFragment;
|
||||
if (isset($this->plugin)) {
|
||||
$path = $this->_pluginPath($this->plugin) . 'src/' . $this->pathFragment;
|
||||
}
|
||||
$prefix = $this->_getPrefix();
|
||||
if ($prefix) {
|
||||
$path .= $prefix . DS;
|
||||
}
|
||||
|
||||
return str_replace('/', DS, $path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Base execute method parses some parameters and sets some properties on the bake tasks.
|
||||
* call when overriding execute()
|
||||
*
|
||||
* @return bool|int|null|void
|
||||
*/
|
||||
public function main()
|
||||
{
|
||||
if (isset($this->params['plugin'])) {
|
||||
$parts = explode('/', $this->params['plugin']);
|
||||
$this->plugin = implode('/', array_map([$this, '_camelize'], $parts));
|
||||
if (strpos($this->plugin, '\\')) {
|
||||
$this->abort('Invalid plugin namespace separator, please use / instead of \ for plugins.');
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (isset($this->params['connection'])) {
|
||||
$this->connection = $this->params['connection'];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes an external shell command and pipes its output to the stdout
|
||||
*
|
||||
* @param string $command the command to execute
|
||||
* @return void
|
||||
* @throws \RuntimeException if any errors occurred during the execution
|
||||
*/
|
||||
public function callProcess($command)
|
||||
{
|
||||
$descriptorSpec = [
|
||||
0 => ['pipe', 'r'],
|
||||
1 => ['pipe', 'w'],
|
||||
2 => ['pipe', 'w'],
|
||||
];
|
||||
$this->_io->verbose('Running ' . $command);
|
||||
$process = proc_open(
|
||||
$command,
|
||||
$descriptorSpec,
|
||||
$pipes
|
||||
);
|
||||
if (!is_resource($process)) {
|
||||
$this->abort('Could not start subprocess.');
|
||||
|
||||
return;
|
||||
}
|
||||
fclose($pipes[0]);
|
||||
|
||||
$output = stream_get_contents($pipes[1]);
|
||||
fclose($pipes[1]);
|
||||
|
||||
$error = stream_get_contents($pipes[2]);
|
||||
fclose($pipes[2]);
|
||||
$exit = proc_close($process);
|
||||
|
||||
if ($exit !== 0) {
|
||||
throw new \RuntimeException($error);
|
||||
}
|
||||
|
||||
$this->out($output);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles splitting up the plugin prefix and classname.
|
||||
*
|
||||
* Sets the plugin parameter and plugin property.
|
||||
*
|
||||
* @param string $name The name to possibly split.
|
||||
* @return string The name without the plugin prefix.
|
||||
*/
|
||||
protected function _getName($name)
|
||||
{
|
||||
if (strpos($name, '.')) {
|
||||
list($plugin, $name) = pluginSplit($name);
|
||||
$this->plugin = $this->params['plugin'] = $plugin;
|
||||
}
|
||||
|
||||
return $name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete empty file in a given path
|
||||
*
|
||||
* @param string $path Path to folder which contains 'empty' file.
|
||||
* @return void
|
||||
*/
|
||||
protected function _deleteEmptyFile($path)
|
||||
{
|
||||
$File = new File($path);
|
||||
if ($File->exists()) {
|
||||
$File->delete();
|
||||
$this->out(sprintf('<success>Deleted</success> `%s`', $path), 1, Shell::QUIET);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the option parser for this task.
|
||||
*
|
||||
* This base class method sets up some commonly used options.
|
||||
*
|
||||
* @return \Cake\Console\ConsoleOptionParser
|
||||
*/
|
||||
public function getOptionParser()
|
||||
{
|
||||
return $this->_setCommonOptions(parent::getOptionParser());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.1.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Bake\Shell\Task;
|
||||
|
||||
use Bake\View\BakeView;
|
||||
use Cake\Console\Shell;
|
||||
use Cake\Core\ConventionsTrait;
|
||||
use Cake\Event\Event;
|
||||
use Cake\Event\EventManager;
|
||||
use Cake\Http\Response;
|
||||
use Cake\Http\ServerRequest as Request;
|
||||
use Cake\View\Exception\MissingTemplateException;
|
||||
use Cake\View\ViewVarsTrait;
|
||||
|
||||
/**
|
||||
* Used by other tasks to generate templated output, Acts as an interface to BakeView
|
||||
*/
|
||||
class BakeTemplateTask extends Shell
|
||||
{
|
||||
use ConventionsTrait;
|
||||
|
||||
use ViewVarsTrait;
|
||||
|
||||
/**
|
||||
* BakeView instance
|
||||
*
|
||||
* @var \Bake\View\BakeView|null
|
||||
*/
|
||||
public $View;
|
||||
|
||||
/**
|
||||
* Get view instance
|
||||
*
|
||||
* @return \Cake\View\View
|
||||
* @triggers Bake.initialize $view
|
||||
*/
|
||||
public function getView()
|
||||
{
|
||||
if ($this->View) {
|
||||
return $this->View;
|
||||
}
|
||||
|
||||
$theme = isset($this->params['theme']) ? $this->params['theme'] : '';
|
||||
|
||||
$viewOptions = [
|
||||
'helpers' => [
|
||||
'Bake.Bake',
|
||||
'Bake.DocBlock',
|
||||
],
|
||||
'theme' => $theme,
|
||||
];
|
||||
|
||||
$view = new BakeView(new Request(), new Response(), null, $viewOptions);
|
||||
$event = new Event('Bake.initialize', $view);
|
||||
EventManager::instance()->dispatch($event);
|
||||
/** @var \Bake\View\BakeView $view */
|
||||
$view = $event->getSubject();
|
||||
$this->View = $view;
|
||||
|
||||
return $this->View;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the template
|
||||
*
|
||||
* @param string $template bake template to render
|
||||
* @param array|null $vars Additional vars to set to template scope.
|
||||
* @return string contents of generated code template
|
||||
*/
|
||||
public function generate($template, $vars = null)
|
||||
{
|
||||
if ($vars !== null) {
|
||||
$this->set($vars);
|
||||
}
|
||||
|
||||
$this->getView()->set($this->viewVars);
|
||||
|
||||
try {
|
||||
return $this->View->render($template);
|
||||
} catch (MissingTemplateException $e) {
|
||||
$this->_io->verbose(sprintf('No bake template found for "%s"', $template));
|
||||
|
||||
return '';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.1.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Bake\Shell\Task;
|
||||
|
||||
/**
|
||||
* Behavior code generator.
|
||||
*
|
||||
* @property \Bake\Shell\Task\BakeTemplateTask $BakeTemplate
|
||||
* @property \Bake\Shell\Task\TestTask $Test
|
||||
*/
|
||||
class BehaviorTask extends SimpleBakeTask
|
||||
{
|
||||
/**
|
||||
* Task name used in path generation.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $pathFragment = 'Model/Behavior/';
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function name()
|
||||
{
|
||||
return 'behavior';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function fileName($name)
|
||||
{
|
||||
return $name . 'Behavior.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function template()
|
||||
{
|
||||
return 'Model/behavior';
|
||||
}
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.1.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Bake\Shell\Task;
|
||||
|
||||
use Cake\Core\Configure;
|
||||
|
||||
/**
|
||||
* Task for creating cells.
|
||||
*
|
||||
* @property \Bake\Shell\Task\BakeTemplateTask $BakeTemplate
|
||||
* @property \Bake\Shell\Task\TestTask $Test
|
||||
*/
|
||||
class CellTask extends SimpleBakeTask
|
||||
{
|
||||
/**
|
||||
* Task name used in path generation.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $pathFragment = 'View/Cell/';
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function name()
|
||||
{
|
||||
return 'cell';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function fileName($name)
|
||||
{
|
||||
return $name . 'Cell.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function template()
|
||||
{
|
||||
return 'View/cell';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get template data.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function templateData()
|
||||
{
|
||||
$prefix = $this->_getPrefix();
|
||||
if ($prefix) {
|
||||
$prefix = '\\' . str_replace('/', '\\', $prefix);
|
||||
}
|
||||
|
||||
$namespace = Configure::read('App.namespace');
|
||||
if ($this->plugin) {
|
||||
$namespace = $this->_pluginNamespace($this->plugin);
|
||||
}
|
||||
|
||||
return compact('namespace', 'prefix');
|
||||
}
|
||||
|
||||
/**
|
||||
* Bake the Cell class and template file.
|
||||
*
|
||||
* @param string $name The name of the cell to make.
|
||||
* @return string
|
||||
*/
|
||||
public function bake($name)
|
||||
{
|
||||
$this->bakeTemplate($name);
|
||||
|
||||
return parent::bake($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bake an empty file for a cell.
|
||||
*
|
||||
* @param string $name The name of the cell a template is needed for.
|
||||
* @return void
|
||||
*/
|
||||
public function bakeTemplate($name)
|
||||
{
|
||||
$restore = $this->pathFragment;
|
||||
|
||||
$this->pathFragment = 'Template/Cell/';
|
||||
$path = $this->getPath();
|
||||
$path .= implode(DS, [$name, 'display.ctp']);
|
||||
|
||||
$this->pathFragment = $restore;
|
||||
|
||||
$this->createFile($path, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the option parser instance and configures it.
|
||||
*
|
||||
* @return \Cake\Console\ConsoleOptionParser
|
||||
*/
|
||||
public function getOptionParser()
|
||||
{
|
||||
$parser = parent::getOptionParser();
|
||||
$parser
|
||||
->addOption('prefix', [
|
||||
'help' => 'The namespace prefix to use.',
|
||||
]);
|
||||
|
||||
return $parser;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 1.7.4
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Bake\Shell\Task;
|
||||
|
||||
/**
|
||||
* Shell code generator.
|
||||
*
|
||||
* @property \Bake\Shell\Task\BakeTemplateTask $BakeTemplate
|
||||
* @property \Bake\Shell\Task\TestTask $Test
|
||||
*/
|
||||
class CommandTask extends SimpleBakeTask
|
||||
{
|
||||
/**
|
||||
* Task name used in path generation.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $pathFragment = 'Command/';
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function name()
|
||||
{
|
||||
return 'command';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function fileName($name)
|
||||
{
|
||||
return $name . 'Command.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function template()
|
||||
{
|
||||
return 'Command/command';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.1.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Bake\Shell\Task;
|
||||
|
||||
/**
|
||||
* Component code generator.
|
||||
*
|
||||
* @property \Bake\Shell\Task\BakeTemplateTask $BakeTemplate
|
||||
* @property \Bake\Shell\Task\TestTask $Test
|
||||
*/
|
||||
class ComponentTask extends SimpleBakeTask
|
||||
{
|
||||
/**
|
||||
* Task name used in path generation.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $pathFragment = 'Controller/Component/';
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function name()
|
||||
{
|
||||
return 'component';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function fileName($name)
|
||||
{
|
||||
return $name . 'Component.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function template()
|
||||
{
|
||||
return 'Controller/component';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.1.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Bake\Shell\Task;
|
||||
|
||||
use Cake\Console\Shell;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\ORM\TableRegistry;
|
||||
|
||||
/**
|
||||
* Task class for creating and updating controller files.
|
||||
*
|
||||
* @property \Bake\Shell\Task\ModelTask $Model
|
||||
* @property \Bake\Shell\Task\BakeTemplateTask $BakeTemplate
|
||||
* @property \Bake\Shell\Task\TestTask $Test
|
||||
*/
|
||||
class ControllerTask extends BakeTask
|
||||
{
|
||||
/**
|
||||
* Tasks to be loaded by this Task
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $tasks = [
|
||||
'Bake.Model',
|
||||
'Bake.BakeTemplate',
|
||||
'Bake.Test',
|
||||
];
|
||||
|
||||
/**
|
||||
* Path fragment for generated code.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $pathFragment = 'Controller/';
|
||||
|
||||
/**
|
||||
* Execution method always used for tasks
|
||||
*
|
||||
* @param string|null $name The name of the controller to bake.
|
||||
* @return null|bool
|
||||
*/
|
||||
public function main($name = null)
|
||||
{
|
||||
parent::main();
|
||||
$name = $this->_getName($name);
|
||||
|
||||
if (empty($name)) {
|
||||
$this->out('Possible controllers based on your current database:');
|
||||
foreach ($this->listAll() as $table) {
|
||||
$this->out('- ' . $this->_camelize($table));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
$controller = $this->_camelize($name);
|
||||
$this->bake($controller);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bake All the controllers at once. Will only bake controllers for models that exist.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function all()
|
||||
{
|
||||
$tables = $this->listAll();
|
||||
foreach ($tables as $table) {
|
||||
TableRegistry::getTableLocator()->clear();
|
||||
$this->main($table);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Assembles and writes a Controller file
|
||||
*
|
||||
* @param string $controllerName Controller name already pluralized and correctly cased.
|
||||
* @return string Baked controller
|
||||
*/
|
||||
public function bake($controllerName)
|
||||
{
|
||||
$this->out("\n" . sprintf('Baking controller class for %s...', $controllerName), 1, Shell::QUIET);
|
||||
|
||||
$actions = [];
|
||||
if (!$this->param('no-actions') && !$this->param('actions')) {
|
||||
$actions = ['index', 'view', 'add', 'edit', 'delete'];
|
||||
}
|
||||
if ($this->param('actions')) {
|
||||
$actions = array_map('trim', explode(',', $this->param('actions')));
|
||||
$actions = array_filter($actions);
|
||||
}
|
||||
|
||||
$helpers = $this->getHelpers();
|
||||
$components = $this->getComponents();
|
||||
|
||||
$prefix = $this->_getPrefix();
|
||||
if ($prefix) {
|
||||
$prefix = '\\' . str_replace('/', '\\', $prefix);
|
||||
}
|
||||
|
||||
$namespace = Configure::read('App.namespace');
|
||||
if ($this->plugin) {
|
||||
$namespace = $this->_pluginNamespace($this->plugin);
|
||||
}
|
||||
|
||||
$currentModelName = $controllerName;
|
||||
$plugin = $this->plugin;
|
||||
if ($plugin) {
|
||||
$plugin .= '.';
|
||||
}
|
||||
|
||||
if (TableRegistry::getTableLocator()->exists($plugin . $currentModelName)) {
|
||||
$modelObj = TableRegistry::getTableLocator()->get($plugin . $currentModelName);
|
||||
} else {
|
||||
$modelObj = TableRegistry::getTableLocator()->get($plugin . $currentModelName, [
|
||||
'connectionName' => $this->connection,
|
||||
]);
|
||||
}
|
||||
|
||||
$pluralName = $this->_variableName($currentModelName);
|
||||
$singularName = $this->_singularName($currentModelName);
|
||||
$singularHumanName = $this->_singularHumanName($controllerName);
|
||||
$pluralHumanName = $this->_variableName($controllerName);
|
||||
|
||||
$defaultModel = sprintf('%s\Model\Table\%sTable', $namespace, $controllerName);
|
||||
if (!class_exists($defaultModel)) {
|
||||
$defaultModel = null;
|
||||
}
|
||||
$entityClassName = $this->_entityName($modelObj->getAlias());
|
||||
|
||||
$data = compact(
|
||||
'actions',
|
||||
'components',
|
||||
'currentModelName',
|
||||
'defaultModel',
|
||||
'entityClassName',
|
||||
'helpers',
|
||||
'modelObj',
|
||||
'namespace',
|
||||
'plugin',
|
||||
'pluralHumanName',
|
||||
'pluralName',
|
||||
'prefix',
|
||||
'singularHumanName',
|
||||
'singularName'
|
||||
);
|
||||
$data['name'] = $controllerName;
|
||||
|
||||
$out = $this->bakeController($controllerName, $data);
|
||||
$this->bakeTest($controllerName);
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate the controller code
|
||||
*
|
||||
* @param string $controllerName The name of the controller.
|
||||
* @param array $data The data to turn into code.
|
||||
* @return string The generated controller file.
|
||||
*/
|
||||
public function bakeController($controllerName, array $data)
|
||||
{
|
||||
$data += [
|
||||
'name' => null,
|
||||
'namespace' => null,
|
||||
'prefix' => null,
|
||||
'actions' => null,
|
||||
'helpers' => null,
|
||||
'components' => null,
|
||||
'plugin' => null,
|
||||
'pluginPath' => null,
|
||||
];
|
||||
|
||||
$this->BakeTemplate->set($data);
|
||||
|
||||
$contents = $this->BakeTemplate->generate('Controller/controller');
|
||||
|
||||
$path = $this->getPath();
|
||||
$filename = $path . $controllerName . 'Controller.php';
|
||||
$this->createFile($filename, $contents);
|
||||
|
||||
return $contents;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assembles and writes a unit test file
|
||||
*
|
||||
* @param string $className Controller class name
|
||||
* @return string|false Baked test
|
||||
*/
|
||||
public function bakeTest($className)
|
||||
{
|
||||
if (!empty($this->params['no-test'])) {
|
||||
return false;
|
||||
}
|
||||
$this->Test->plugin = $this->plugin;
|
||||
$this->Test->connection = $this->connection;
|
||||
$this->Test->interactive = $this->interactive;
|
||||
|
||||
return $this->Test->bake('Controller', $className);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of components for the controller.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getComponents()
|
||||
{
|
||||
$components = [];
|
||||
if (!empty($this->params['components'])) {
|
||||
$components = explode(',', $this->params['components']);
|
||||
$components = array_values(array_filter(array_map('trim', $components)));
|
||||
}
|
||||
|
||||
return $components;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of helpers for the controller.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getHelpers()
|
||||
{
|
||||
$helpers = [];
|
||||
if (!empty($this->params['helpers'])) {
|
||||
$helpers = explode(',', $this->params['helpers']);
|
||||
$helpers = array_values(array_filter(array_map('trim', $helpers)));
|
||||
}
|
||||
|
||||
return $helpers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs and gets the list of possible controllers from database
|
||||
*
|
||||
* @return array Set of controllers
|
||||
*/
|
||||
public function listAll()
|
||||
{
|
||||
$this->Model->connection = $this->connection;
|
||||
|
||||
return $this->Model->listUnskipped();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the option parser instance and configures it.
|
||||
*
|
||||
* @return \Cake\Console\ConsoleOptionParser
|
||||
*/
|
||||
public function getOptionParser()
|
||||
{
|
||||
$parser = parent::getOptionParser();
|
||||
$parser->setDescription(
|
||||
'Bake a controller skeleton.'
|
||||
)->addArgument('name', [
|
||||
'help' => 'Name of the controller to bake (without the `Controller` suffix). ' .
|
||||
'You can use Plugin.name to bake controllers into plugins.',
|
||||
])->addOption('components', [
|
||||
'help' => 'The comma separated list of components to use.',
|
||||
])->addOption('helpers', [
|
||||
'help' => 'The comma separated list of helpers to use.',
|
||||
])->addOption('prefix', [
|
||||
'help' => 'The namespace/routing prefix to use.',
|
||||
])->addOption('actions', [
|
||||
'help' => 'The comma separated list of actions to generate. ' .
|
||||
'You can include custom methods provided by your template set here.',
|
||||
])->addOption('no-test', [
|
||||
'boolean' => true,
|
||||
'help' => 'Do not generate a test skeleton.',
|
||||
])->addOption('no-actions', [
|
||||
'boolean' => true,
|
||||
'help' => 'Do not generate basic CRUD action methods.',
|
||||
])->addSubcommand('all', [
|
||||
'help' => 'Bake all controllers with CRUD methods.',
|
||||
]);
|
||||
|
||||
return $parser;
|
||||
}
|
||||
}
|
||||
+466
@@ -0,0 +1,466 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.1.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Bake\Shell\Task;
|
||||
|
||||
use Cake\Console\Shell;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Database\Exception;
|
||||
use Cake\Database\Schema\TableSchema;
|
||||
use Cake\Datasource\ConnectionManager;
|
||||
use Cake\ORM\TableRegistry;
|
||||
use Cake\Utility\Inflector;
|
||||
use Cake\Utility\Text;
|
||||
use DateTimeInterface;
|
||||
|
||||
/**
|
||||
* Task class for creating and updating fixtures files.
|
||||
*
|
||||
* @property \Bake\Shell\Task\BakeTemplateTask $BakeTemplate
|
||||
* @property \Bake\Shell\Task\ModelTask $Model
|
||||
*/
|
||||
class FixtureTask extends BakeTask
|
||||
{
|
||||
/**
|
||||
* Tasks to be loaded by this Task
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $tasks = [
|
||||
'Bake.Model',
|
||||
'Bake.BakeTemplate',
|
||||
];
|
||||
|
||||
/**
|
||||
* Get the file path.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getPath()
|
||||
{
|
||||
$dir = 'Fixture/';
|
||||
$path = defined('TESTS') ? TESTS . $dir : ROOT . DS . 'tests' . DS . $dir;
|
||||
if (isset($this->plugin)) {
|
||||
$path = $this->_pluginPath($this->plugin) . 'tests/' . $dir;
|
||||
}
|
||||
|
||||
return str_replace('/', DS, $path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the option parser instance and configures it.
|
||||
*
|
||||
* @return \Cake\Console\ConsoleOptionParser
|
||||
*/
|
||||
public function getOptionParser()
|
||||
{
|
||||
$parser = parent::getOptionParser();
|
||||
|
||||
$parser = $parser->setDescription(
|
||||
'Generate fixtures for use with the test suite. You can use `bake fixture all` to bake all fixtures.'
|
||||
)->addArgument('name', [
|
||||
'help' => 'Name of the fixture to bake (without the `Fixture` suffix). ' .
|
||||
'You can use Plugin.name to bake plugin fixtures.',
|
||||
])->addOption('table', [
|
||||
'help' => 'The table name if it does not follow conventions.',
|
||||
])->addOption('count', [
|
||||
'help' => 'When using generated data, the number of records to include in the fixture(s).',
|
||||
'short' => 'n',
|
||||
'default' => 1,
|
||||
])->addOption('schema', [
|
||||
'help' => 'Create a fixture that imports schema, instead of dumping a schema snapshot into the fixture.',
|
||||
'short' => 's',
|
||||
'boolean' => true,
|
||||
])->addOption('records', [
|
||||
'help' => 'Generate a fixture with records from the non-test database.' .
|
||||
' Used with --count and --conditions to limit which records are added to the fixture.',
|
||||
'short' => 'r',
|
||||
'boolean' => true,
|
||||
])->addOption('conditions', [
|
||||
'help' => 'The SQL snippet to use when importing records.',
|
||||
'default' => '1=1',
|
||||
])->addSubcommand('all', [
|
||||
'help' => 'Bake all fixture files for tables in the chosen connection.',
|
||||
]);
|
||||
|
||||
return $parser;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execution method always used for tasks
|
||||
* Handles dispatching to interactive, named, or all processes.
|
||||
*
|
||||
* @param string|null $name The name of the fixture to bake.
|
||||
* @return null|bool
|
||||
*/
|
||||
public function main($name = null)
|
||||
{
|
||||
parent::main();
|
||||
$name = $this->_getName($name);
|
||||
|
||||
if (empty($name)) {
|
||||
$this->out('Choose a fixture to bake from the following:');
|
||||
foreach ($this->Model->listUnskipped() as $table) {
|
||||
$this->out('- ' . $this->_camelize($table));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
$table = null;
|
||||
if (isset($this->params['table'])) {
|
||||
$table = $this->params['table'];
|
||||
}
|
||||
$model = $this->_camelize($name);
|
||||
$this->bake($model, $table);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bake All the Fixtures at once. Will only bake fixtures for models that exist.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function all()
|
||||
{
|
||||
$tables = $this->Model->listUnskipped();
|
||||
|
||||
foreach ($tables as $table) {
|
||||
$this->main($table);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Assembles and writes a Fixture file
|
||||
*
|
||||
* @param string $model Name of model to bake.
|
||||
* @param string|null $useTable Name of table to use.
|
||||
* @return string Baked fixture content
|
||||
* @throws \RuntimeException
|
||||
*/
|
||||
public function bake($model, $useTable = null)
|
||||
{
|
||||
$table = $schema = $records = $import = $modelImport = null;
|
||||
|
||||
if (!$useTable) {
|
||||
$useTable = Inflector::tableize($model);
|
||||
} elseif ($useTable !== Inflector::tableize($model)) {
|
||||
$table = $useTable;
|
||||
}
|
||||
|
||||
$importBits = [];
|
||||
if (!empty($this->params['schema'])) {
|
||||
$modelImport = true;
|
||||
$importBits[] = "'table' => '{$useTable}'";
|
||||
}
|
||||
if (!empty($importBits) && $this->connection !== 'default') {
|
||||
$importBits[] = "'connection' => '{$this->connection}'";
|
||||
}
|
||||
if (!empty($importBits)) {
|
||||
$import = sprintf("[%s]", implode(', ', $importBits));
|
||||
}
|
||||
|
||||
try {
|
||||
$data = $this->readSchema($model, $useTable);
|
||||
} catch (Exception $e) {
|
||||
TableRegistry::getTableLocator()->remove($model);
|
||||
$useTable = Inflector::underscore($model);
|
||||
$table = $useTable;
|
||||
$data = $this->readSchema($model, $useTable);
|
||||
}
|
||||
|
||||
if ($modelImport === null) {
|
||||
$schema = $this->_generateSchema($data);
|
||||
}
|
||||
|
||||
if (empty($this->params['records'])) {
|
||||
$recordCount = 1;
|
||||
if (isset($this->params['count'])) {
|
||||
$recordCount = $this->params['count'];
|
||||
}
|
||||
$records = $this->_makeRecordString($this->_generateRecords($data, $recordCount));
|
||||
}
|
||||
if (!empty($this->params['records'])) {
|
||||
$records = $this->_makeRecordString($this->_getRecordsFromTable($model, $useTable));
|
||||
}
|
||||
|
||||
return $this->generateFixtureFile($model, compact('records', 'table', 'schema', 'import'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get schema metadata for the current table mapping.
|
||||
*
|
||||
* @param string $name The model alias to use
|
||||
* @param string $table The table name to get schema metadata for.
|
||||
* @return \Cake\Database\Schema\TableSchema
|
||||
*/
|
||||
public function readSchema($name, $table)
|
||||
{
|
||||
$connection = ConnectionManager::get($this->connection);
|
||||
|
||||
if (TableRegistry::getTableLocator()->exists($name)) {
|
||||
$model = TableRegistry::getTableLocator()->get($name);
|
||||
} else {
|
||||
$model = TableRegistry::getTableLocator()->get($name, [
|
||||
'table' => $table,
|
||||
'connection' => $connection,
|
||||
]);
|
||||
}
|
||||
|
||||
return $model->getSchema();
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate the fixture file, and write to disk
|
||||
*
|
||||
* @param string $model name of the model being generated
|
||||
* @param array $otherVars Contents of the fixture file.
|
||||
* @return string Content saved into fixture file.
|
||||
*/
|
||||
public function generateFixtureFile($model, array $otherVars)
|
||||
{
|
||||
$defaults = [
|
||||
'name' => $model,
|
||||
'table' => null,
|
||||
'schema' => null,
|
||||
'records' => null,
|
||||
'import' => null,
|
||||
'fields' => null,
|
||||
'namespace' => Configure::read('App.namespace'),
|
||||
];
|
||||
if ($this->plugin) {
|
||||
$defaults['namespace'] = $this->_pluginNamespace($this->plugin);
|
||||
}
|
||||
$vars = $otherVars + $defaults;
|
||||
|
||||
$path = $this->getPath();
|
||||
$filename = $vars['name'] . 'Fixture.php';
|
||||
|
||||
$this->BakeTemplate->set('model', $model);
|
||||
$this->BakeTemplate->set($vars);
|
||||
$content = $this->BakeTemplate->generate('tests/fixture');
|
||||
|
||||
$this->out("\n" . sprintf('Baking test fixture for %s...', $model), 1, Shell::QUIET);
|
||||
$this->createFile($path . $filename, $content);
|
||||
$emptyFile = $path . 'empty';
|
||||
$this->_deleteEmptyFile($emptyFile);
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a string representation of a schema.
|
||||
*
|
||||
* @param \Cake\Database\Schema\TableSchema $table Table schema
|
||||
* @return string fields definitions
|
||||
*/
|
||||
protected function _generateSchema(TableSchema $table)
|
||||
{
|
||||
$cols = $indexes = $constraints = [];
|
||||
foreach ($table->columns() as $field) {
|
||||
$fieldData = $table->getColumn($field);
|
||||
$properties = implode(', ', $this->_values($fieldData));
|
||||
$cols[] = " '$field' => [$properties],";
|
||||
}
|
||||
foreach ($table->indexes() as $index) {
|
||||
$fieldData = $table->getIndex($index);
|
||||
$properties = implode(', ', $this->_values($fieldData));
|
||||
$indexes[] = " '$index' => [$properties],";
|
||||
}
|
||||
foreach ($table->constraints() as $index) {
|
||||
$fieldData = $table->getConstraint($index);
|
||||
$properties = implode(', ', $this->_values($fieldData));
|
||||
$constraints[] = " '$index' => [$properties],";
|
||||
}
|
||||
$options = $this->_values($table->getOptions());
|
||||
|
||||
$content = implode("\n", $cols) . "\n";
|
||||
if (!empty($indexes)) {
|
||||
$content .= " '_indexes' => [\n" . implode("\n", $indexes) . "\n ],\n";
|
||||
}
|
||||
if (!empty($constraints)) {
|
||||
$content .= " '_constraints' => [\n" . implode("\n", $constraints) . "\n ],\n";
|
||||
}
|
||||
if (!empty($options)) {
|
||||
foreach ($options as &$option) {
|
||||
$option = ' ' . $option;
|
||||
}
|
||||
$content .= " '_options' => [\n" . implode(",\n", $options) . "\n ],\n";
|
||||
}
|
||||
|
||||
return "[\n$content ]";
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats Schema columns from Model Object
|
||||
*
|
||||
* @param array $values options keys(type, null, default, key, length, extra)
|
||||
* @return array Formatted values
|
||||
*/
|
||||
protected function _values($values)
|
||||
{
|
||||
$vals = [];
|
||||
if (!is_array($values)) {
|
||||
return $vals;
|
||||
}
|
||||
foreach ($values as $key => $val) {
|
||||
if (is_array($val)) {
|
||||
$vals[] = "'{$key}' => [" . implode(", ", $this->_values($val)) . "]";
|
||||
} else {
|
||||
$val = var_export($val, true);
|
||||
if ($val === 'NULL') {
|
||||
$val = 'null';
|
||||
}
|
||||
if (!is_numeric($key)) {
|
||||
$vals[] = "'{$key}' => {$val}";
|
||||
} else {
|
||||
$vals[] = "{$val}";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $vals;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate String representation of Records
|
||||
*
|
||||
* @param \Cake\Database\Schema\TableSchema $table Table schema array
|
||||
* @param int $recordCount The number of records to generate.
|
||||
* @return array Array of records to use in the fixture.
|
||||
*/
|
||||
protected function _generateRecords(TableSchema $table, $recordCount = 1)
|
||||
{
|
||||
$records = [];
|
||||
for ($i = 0; $i < $recordCount; $i++) {
|
||||
$record = [];
|
||||
foreach ($table->columns() as $field) {
|
||||
$fieldInfo = $table->getColumn($field);
|
||||
$insert = '';
|
||||
switch ($fieldInfo['type']) {
|
||||
case 'decimal':
|
||||
$insert = $i + 1.5;
|
||||
break;
|
||||
case 'biginteger':
|
||||
case 'integer':
|
||||
case 'float':
|
||||
case 'smallinteger':
|
||||
case 'tinyinteger':
|
||||
$insert = $i + 1;
|
||||
break;
|
||||
case 'string':
|
||||
case 'binary':
|
||||
$isPrimary = in_array($field, $table->primaryKey());
|
||||
if ($isPrimary) {
|
||||
$insert = Text::uuid();
|
||||
} else {
|
||||
$insert = "Lorem ipsum dolor sit amet";
|
||||
if (!empty($fieldInfo['length'])) {
|
||||
$insert = substr($insert, 0, (int)$fieldInfo['length'] > 2 ? (int)$fieldInfo['length'] - 2 : (int)$fieldInfo['length']);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 'timestamp':
|
||||
$insert = time();
|
||||
break;
|
||||
case 'datetime':
|
||||
$insert = date('Y-m-d H:i:s');
|
||||
break;
|
||||
case 'date':
|
||||
$insert = date('Y-m-d');
|
||||
break;
|
||||
case 'time':
|
||||
$insert = date('H:i:s');
|
||||
break;
|
||||
case 'boolean':
|
||||
$insert = 1;
|
||||
break;
|
||||
case 'text':
|
||||
$insert = "Lorem ipsum dolor sit amet, aliquet feugiat.";
|
||||
$insert .= " Convallis morbi fringilla gravida,";
|
||||
$insert .= " phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin";
|
||||
$insert .= " venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla";
|
||||
$insert .= " vestibulum massa neque ut et, id hendrerit sit,";
|
||||
$insert .= " feugiat in taciti enim proin nibh, tempor dignissim, rhoncus";
|
||||
$insert .= " duis vestibulum nunc mattis convallis.";
|
||||
break;
|
||||
case 'uuid':
|
||||
$insert = Text::uuid();
|
||||
break;
|
||||
}
|
||||
$record[$field] = $insert;
|
||||
}
|
||||
$records[] = $record;
|
||||
}
|
||||
|
||||
return $records;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a $records array into a string.
|
||||
*
|
||||
* @param array $records Array of records to be converted to string
|
||||
* @return string A string value of the $records array.
|
||||
*/
|
||||
protected function _makeRecordString($records)
|
||||
{
|
||||
$out = "[\n";
|
||||
foreach ($records as $record) {
|
||||
$values = [];
|
||||
foreach ($record as $field => $value) {
|
||||
if ($value instanceof DateTimeInterface) {
|
||||
$value = $value->format('Y-m-d H:i:s');
|
||||
}
|
||||
$val = var_export($value, true);
|
||||
if ($val === 'NULL') {
|
||||
$val = 'null';
|
||||
}
|
||||
$values[] = " '$field' => $val";
|
||||
}
|
||||
$out .= " [\n";
|
||||
$out .= implode(",\n", $values);
|
||||
$out .= ",\n ],\n";
|
||||
}
|
||||
$out .= " ]";
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interact with the user to get a custom SQL condition and use that to extract data
|
||||
* to build a fixture.
|
||||
*
|
||||
* @param string $modelName name of the model to take records from.
|
||||
* @param string|null $useTable Name of table to use.
|
||||
* @return array Array of records.
|
||||
*/
|
||||
protected function _getRecordsFromTable($modelName, $useTable = null)
|
||||
{
|
||||
$recordCount = (isset($this->params['count']) ? $this->params['count'] : 10);
|
||||
$conditions = (isset($this->params['conditions']) ? $this->params['conditions'] : '1=1');
|
||||
if (TableRegistry::getTableLocator()->exists($modelName)) {
|
||||
$model = TableRegistry::getTableLocator()->get($modelName);
|
||||
} else {
|
||||
$model = TableRegistry::getTableLocator()->get($modelName, [
|
||||
'table' => $useTable,
|
||||
'connection' => ConnectionManager::get($this->connection),
|
||||
]);
|
||||
}
|
||||
$records = $model->find('all')
|
||||
->where($conditions)
|
||||
->limit($recordCount)
|
||||
->enableHydration(false);
|
||||
|
||||
return $records->toArray();
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 1.0.9
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Bake\Shell\Task;
|
||||
|
||||
/**
|
||||
* ShellHelper code generator.
|
||||
*
|
||||
* @property \Bake\Shell\Task\BakeTemplateTask $BakeTemplate
|
||||
* @property \Bake\Shell\Task\TestTask $Test
|
||||
*/
|
||||
class FormTask extends SimpleBakeTask
|
||||
{
|
||||
/**
|
||||
* Task name used in path generation.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $pathFragment = 'Form/';
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function name()
|
||||
{
|
||||
return 'form';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function fileName($name)
|
||||
{
|
||||
return $name . 'Form.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function template()
|
||||
{
|
||||
return 'Form/form';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.1.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Bake\Shell\Task;
|
||||
|
||||
/**
|
||||
* Helper code generator.
|
||||
*
|
||||
* @property \Bake\Shell\Task\BakeTemplateTask $BakeTemplate
|
||||
* @property \Bake\Shell\Task\TestTask $Test
|
||||
*/
|
||||
class HelperTask extends SimpleBakeTask
|
||||
{
|
||||
/**
|
||||
* Task name used in path generation.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $pathFragment = 'View/Helper/';
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function name()
|
||||
{
|
||||
return 'helper';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function fileName($name)
|
||||
{
|
||||
return $name . 'Helper.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function template()
|
||||
{
|
||||
return 'View/helper';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 1.1.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Bake\Shell\Task;
|
||||
|
||||
use Cake\Utility\Inflector;
|
||||
|
||||
/**
|
||||
* Mailer code generator.
|
||||
*
|
||||
* @property \Bake\Shell\Task\BakeTemplateTask $BakeTemplate
|
||||
* @property \Bake\Shell\Task\TestTask $Test
|
||||
*/
|
||||
class MailerTask extends SimpleBakeTask
|
||||
{
|
||||
/**
|
||||
* Task name used in path generation.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $pathFragment = 'Mailer/';
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function name()
|
||||
{
|
||||
return 'mailer';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function fileName($name)
|
||||
{
|
||||
return $name . 'Mailer.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function template()
|
||||
{
|
||||
return 'Mailer/mailer';
|
||||
}
|
||||
|
||||
/**
|
||||
* Bake the Mailer class and html/text layout files.
|
||||
*
|
||||
* @param string $name The name of the mailer to make.
|
||||
* @return string
|
||||
*/
|
||||
public function bake($name)
|
||||
{
|
||||
$this->bakeLayouts($name);
|
||||
|
||||
return parent::bake($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bake empty layout files for html/text emails.
|
||||
*
|
||||
* @param string $name The name of the mailer layouts are needed for.
|
||||
* @return void
|
||||
*/
|
||||
public function bakeLayouts($name)
|
||||
{
|
||||
$restore = $this->pathFragment;
|
||||
$layoutsPath = implode(DS, ['Template', 'Layout', 'Email']);
|
||||
|
||||
foreach (['html', 'text'] as $type) {
|
||||
$this->pathFragment = implode(DS, [$layoutsPath, $type, Inflector::underscore($name) . '.ctp']);
|
||||
$path = $this->getPath();
|
||||
$this->createFile($path, '');
|
||||
}
|
||||
|
||||
$this->pathFragment = $restore;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 1.3.6
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Bake\Shell\Task;
|
||||
|
||||
/**
|
||||
* Middleware code generator.
|
||||
*
|
||||
* @property \Bake\Shell\Task\BakeTemplateTask $BakeTemplate
|
||||
* @property \Bake\Shell\Task\TestTask $Test
|
||||
*/
|
||||
class MiddlewareTask extends SimpleBakeTask
|
||||
{
|
||||
/**
|
||||
* Task name used in path generation.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $pathFragment = 'Middleware/';
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function name()
|
||||
{
|
||||
return 'middleware';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function fileName($name)
|
||||
{
|
||||
return $name . 'Middleware.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function template()
|
||||
{
|
||||
return 'Middleware/middleware';
|
||||
}
|
||||
}
|
||||
+1220
File diff suppressed because it is too large.
Load diff
+392
@@ -0,0 +1,392 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.1.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Bake\Shell\Task;
|
||||
|
||||
use Cake\Core\App;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Core\Plugin;
|
||||
use Cake\Filesystem\File;
|
||||
use Cake\Filesystem\Folder;
|
||||
use Cake\Utility\Inflector;
|
||||
|
||||
/**
|
||||
* The Plugin Task handles creating an empty plugin, ready to be used
|
||||
*
|
||||
* @property \Bake\Shell\Task\BakeTemplateTask $BakeTemplate
|
||||
*/
|
||||
class PluginTask extends BakeTask
|
||||
{
|
||||
/**
|
||||
* Tasks this task uses.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $tasks = [
|
||||
'Bake.BakeTemplate',
|
||||
];
|
||||
|
||||
/**
|
||||
* Plugin path.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $path;
|
||||
|
||||
/**
|
||||
* initialize
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function initialize()
|
||||
{
|
||||
$this->path = current(App::path('Plugin'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Execution method always used for tasks
|
||||
*
|
||||
* @param string|null $name The name of the plugin to bake.
|
||||
* @return null|bool
|
||||
*/
|
||||
public function main($name = null)
|
||||
{
|
||||
if (empty($name)) {
|
||||
$this->err('<error>You must provide a plugin name in CamelCase format.</error>');
|
||||
$this->err('To make an "MyExample" plugin, run <info>`cake bake plugin MyExample`</info>.');
|
||||
|
||||
return false;
|
||||
}
|
||||
$parts = explode('/', $name);
|
||||
$plugin = implode('/', array_map([$this, '_camelize'], $parts));
|
||||
|
||||
$pluginPath = $this->_pluginPath($plugin);
|
||||
if (is_dir($pluginPath)) {
|
||||
$this->out(sprintf('Plugin: %s already exists, no action taken', $plugin));
|
||||
$this->out(sprintf('Path: %s', $pluginPath));
|
||||
|
||||
return false;
|
||||
}
|
||||
if (!$this->bake($plugin)) {
|
||||
$this->abort(sprintf("An error occurred trying to bake: %s in %s", $plugin, $this->path . $plugin));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bake the plugin's contents
|
||||
*
|
||||
* Also update the autoloader and the root composer.json file if it can be found
|
||||
*
|
||||
* @param string $plugin Name of the plugin in CamelCased format
|
||||
* @return bool|null
|
||||
*/
|
||||
public function bake($plugin)
|
||||
{
|
||||
$pathOptions = App::path('Plugin');
|
||||
if (count($pathOptions) > 1) {
|
||||
$this->findPath($pathOptions);
|
||||
}
|
||||
$this->out(sprintf("<info>Plugin Name:</info> %s", $plugin));
|
||||
$this->out(sprintf("<info>Plugin Directory:</info> %s", $this->path . $plugin));
|
||||
$this->hr();
|
||||
|
||||
$looksGood = $this->in('Look okay?', ['y', 'n', 'q'], 'y');
|
||||
|
||||
if (strtolower($looksGood) !== 'y') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$this->_generateFiles($plugin, $this->path);
|
||||
|
||||
$this->_modifyAutoloader($plugin, $this->path);
|
||||
$this->_modifyApplication($plugin);
|
||||
|
||||
$this->hr();
|
||||
$this->out(sprintf('<success>Created:</success> %s in %s', $plugin, $this->path . $plugin), 2);
|
||||
|
||||
$emptyFile = $this->path . 'empty';
|
||||
$this->_deleteEmptyFile($emptyFile);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Modify the application class
|
||||
*
|
||||
* @param string $plugin Name of plugin
|
||||
* the plugin
|
||||
* @return void
|
||||
*/
|
||||
protected function _modifyApplication($plugin)
|
||||
{
|
||||
$application = new File(ROOT . DS . 'src' . DS . 'Application.php', false);
|
||||
if (!$application->exists()) {
|
||||
$this->err('<warning>Could not update application Application.php file, as it could not be found.</warning>');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->dispatchShell('plugin', 'load', $plugin);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate all files for a plugin
|
||||
*
|
||||
* Find the first path which contains `src/Template/Bake/Plugin` that contains
|
||||
* something, and use that as the template to recursively render a plugin's
|
||||
* contents. Allows the creation of a bake them containing a `Plugin` folder
|
||||
* to provide customized bake output for plugins.
|
||||
*
|
||||
* @param string $pluginName the CamelCase name of the plugin
|
||||
* @param string $path the path to the plugins dir (the containing folder)
|
||||
* @return void
|
||||
*/
|
||||
protected function _generateFiles($pluginName, $path)
|
||||
{
|
||||
$namespace = str_replace('/', '\\', $pluginName);
|
||||
$baseNamespace = Configure::read('App.namespace');
|
||||
|
||||
$name = $pluginName;
|
||||
$vendor = 'your-name-here';
|
||||
if (strpos($pluginName, '/') !== false) {
|
||||
list($vendor, $name) = explode('/', $pluginName);
|
||||
}
|
||||
$package = $vendor . '/' . $name;
|
||||
|
||||
$this->BakeTemplate->set([
|
||||
'package' => $package,
|
||||
'namespace' => $namespace,
|
||||
'baseNamespace' => $baseNamespace,
|
||||
'plugin' => $pluginName,
|
||||
'routePath' => Inflector::dasherize($pluginName),
|
||||
'path' => $path,
|
||||
'root' => ROOT,
|
||||
]);
|
||||
|
||||
$root = $path . $pluginName . DS;
|
||||
|
||||
$paths = [];
|
||||
if (!empty($this->params['theme'])) {
|
||||
$paths[] = Plugin::path($this->params['theme']) . 'src/Template/';
|
||||
}
|
||||
|
||||
$paths = array_merge($paths, Configure::read('App.paths.templates'));
|
||||
$paths[] = Plugin::path('Bake') . 'src/Template/';
|
||||
|
||||
do {
|
||||
$templatesPath = array_shift($paths) . 'Bake/Plugin';
|
||||
$templatesDir = new Folder($templatesPath);
|
||||
$templates = $templatesDir->findRecursive('.*\.(twig|ctp)');
|
||||
} while (!$templates);
|
||||
|
||||
sort($templates);
|
||||
foreach ($templates as $template) {
|
||||
$template = substr($template, strrpos($template, 'Plugin' . DIRECTORY_SEPARATOR) + 7, -4);
|
||||
$template = rtrim($template, '.');
|
||||
$this->_generateFile($template, $root);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a file
|
||||
*
|
||||
* @param string $template The template to render
|
||||
* @param string $root The path to the plugin's root
|
||||
* @return void
|
||||
*/
|
||||
protected function _generateFile($template, $root)
|
||||
{
|
||||
$this->out(sprintf('Generating %s file...', $template));
|
||||
$out = $this->BakeTemplate->generate('Plugin/' . $template);
|
||||
$this->createFile($root . $template, $out);
|
||||
}
|
||||
|
||||
/**
|
||||
* Modifies App's composer.json to include the plugin and tries to call
|
||||
* composer dump-autoload to refresh the autoloader cache
|
||||
*
|
||||
* @param string $plugin Name of plugin
|
||||
* @param string $path The path to save the phpunit.xml file to.
|
||||
* @return bool True if composer could be modified correctly
|
||||
*/
|
||||
protected function _modifyAutoloader($plugin, $path)
|
||||
{
|
||||
$file = $this->_rootComposerFilePath();
|
||||
|
||||
if (!file_exists($file)) {
|
||||
$this->out(sprintf('<info>Main composer file %s not found</info>', $file));
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$autoloadPath = str_replace(ROOT, '.', $this->path);
|
||||
$autoloadPath = str_replace('\\', '/', $autoloadPath);
|
||||
$namespace = str_replace('/', '\\', $plugin);
|
||||
|
||||
$config = json_decode(file_get_contents($file), true);
|
||||
$config['autoload']['psr-4'][$namespace . '\\'] = $autoloadPath . $plugin . "/src/";
|
||||
$config['autoload-dev']['psr-4'][$namespace . '\\Test\\'] = $autoloadPath . $plugin . "/tests/";
|
||||
|
||||
$this->out('<info>Modifying composer autoloader</info>');
|
||||
|
||||
$out = json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n";
|
||||
$this->createFile($file, $out);
|
||||
|
||||
$composer = $this->findComposer();
|
||||
|
||||
if (!$composer) {
|
||||
$this->abort('Could not locate composer. Add composer to your PATH, or use the --composer option.');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
$cwd = getcwd();
|
||||
|
||||
// Windows makes running multiple commands at once hard.
|
||||
chdir(dirname($this->_rootComposerFilePath()));
|
||||
$command = 'php ' . escapeshellarg($composer) . ' dump-autoload';
|
||||
$this->callProcess($command);
|
||||
|
||||
chdir($cwd);
|
||||
} catch (\RuntimeException $e) {
|
||||
$error = $e->getMessage();
|
||||
$this->abort(sprintf('Could not run `composer dump-autoload`: %s', $error));
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The path to the main application's composer file
|
||||
*
|
||||
* This is a test isolation wrapper
|
||||
*
|
||||
* @return string the abs file path
|
||||
*/
|
||||
protected function _rootComposerFilePath()
|
||||
{
|
||||
return ROOT . DS . 'composer.json';
|
||||
}
|
||||
|
||||
/**
|
||||
* find and change $this->path to the user selection
|
||||
*
|
||||
* @param array $pathOptions The list of paths to look in.
|
||||
* @return void
|
||||
*/
|
||||
public function findPath(array $pathOptions)
|
||||
{
|
||||
$valid = false;
|
||||
foreach ($pathOptions as $i => $path) {
|
||||
if (!is_dir($path)) {
|
||||
unset($pathOptions[$i]);
|
||||
}
|
||||
}
|
||||
$pathOptions = array_values($pathOptions);
|
||||
$max = count($pathOptions);
|
||||
|
||||
if ($max === 0) {
|
||||
$this->err('No valid plugin paths found! Please configure a plugin path that exists.');
|
||||
throw new \RuntimeException();
|
||||
}
|
||||
|
||||
if ($max === 1) {
|
||||
$this->path = $pathOptions[0];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$choice = null;
|
||||
while (!$valid) {
|
||||
foreach ($pathOptions as $i => $option) {
|
||||
$this->out($i + 1 . '. ' . $option);
|
||||
}
|
||||
$prompt = 'Choose a plugin path from the paths above.';
|
||||
$choice = (int)$this->in($prompt, null, '1');
|
||||
if ($choice > 0 && $choice <= $max) {
|
||||
$valid = true;
|
||||
}
|
||||
}
|
||||
$this->path = $pathOptions[$choice - 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the option parser instance and configures it.
|
||||
*
|
||||
* @return \Cake\Console\ConsoleOptionParser
|
||||
*/
|
||||
public function getOptionParser()
|
||||
{
|
||||
$parser = parent::getOptionParser();
|
||||
$parser->setDescription(
|
||||
'Create the directory structure, AppController class and testing setup for a new plugin. ' .
|
||||
'Can create plugins in any of your bootstrapped plugin paths.'
|
||||
)->addArgument('name', [
|
||||
'help' => 'CamelCased name of the plugin to create.',
|
||||
])->addOption('composer', [
|
||||
'default' => ROOT . DS . 'composer.phar',
|
||||
'help' => 'The path to the composer executable.',
|
||||
])->removeOption('plugin');
|
||||
|
||||
return $parser;
|
||||
}
|
||||
|
||||
/**
|
||||
* Uses either the CLI option or looks in $PATH and cwd for composer.
|
||||
*
|
||||
* @return string|bool Either the path to composer or false if it cannot be found.
|
||||
*/
|
||||
public function findComposer()
|
||||
{
|
||||
if (!empty($this->params['composer'])) {
|
||||
$path = $this->params['composer'];
|
||||
if (file_exists($path)) {
|
||||
return $path;
|
||||
}
|
||||
}
|
||||
$composer = false;
|
||||
$path = env('PATH');
|
||||
if (!empty($path)) {
|
||||
$paths = explode(PATH_SEPARATOR, $path);
|
||||
$composer = $this->_searchPath($paths);
|
||||
}
|
||||
|
||||
return $composer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Search the $PATH for composer.
|
||||
*
|
||||
* @param array $path The paths to search.
|
||||
* @return string|bool
|
||||
*/
|
||||
protected function _searchPath($path)
|
||||
{
|
||||
$composer = ['composer.phar', 'composer'];
|
||||
foreach ($path as $dir) {
|
||||
foreach ($composer as $cmd) {
|
||||
if (is_file($dir . DS . $cmd)) {
|
||||
$this->_io->verbose('Found composer executable in ' . $dir);
|
||||
|
||||
return $dir . DS . $cmd;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 1.1.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Bake\Shell\Task;
|
||||
|
||||
/**
|
||||
* ShellHelper code generator.
|
||||
*
|
||||
* @property \Bake\Shell\Task\BakeTemplateTask $BakeTemplate
|
||||
* @property \Bake\Shell\Task\TestTask $Test
|
||||
*/
|
||||
class ShellHelperTask extends SimpleBakeTask
|
||||
{
|
||||
/**
|
||||
* Task name used in path generation.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $pathFragment = 'Shell/Helper/';
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function name()
|
||||
{
|
||||
return 'shell_helper';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function fileName($name)
|
||||
{
|
||||
return $name . 'Helper.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function template()
|
||||
{
|
||||
return 'Shell/helper';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.1.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Bake\Shell\Task;
|
||||
|
||||
/**
|
||||
* Shell code generator.
|
||||
*
|
||||
* @property \Bake\Shell\Task\BakeTemplateTask $BakeTemplate
|
||||
* @property \Bake\Shell\Task\TestTask $Test
|
||||
*/
|
||||
class ShellTask extends SimpleBakeTask
|
||||
{
|
||||
/**
|
||||
* Task name used in path generation.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $pathFragment = 'Shell/';
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function name()
|
||||
{
|
||||
return 'shell';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function fileName($name)
|
||||
{
|
||||
return $name . 'Shell.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function template()
|
||||
{
|
||||
return 'Shell/shell';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.1.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Bake\Shell\Task;
|
||||
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Utility\Inflector;
|
||||
|
||||
/**
|
||||
* Base class for simple bake tasks code generator.
|
||||
*
|
||||
* @property \Bake\Shell\Task\BakeTemplateTask $BakeTemplate
|
||||
* @property \Bake\Shell\Task\TestTask $Test
|
||||
*/
|
||||
abstract class SimpleBakeTask extends BakeTask
|
||||
{
|
||||
/**
|
||||
* Tasks to be loaded by this Task
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $tasks = [
|
||||
'Bake.BakeTemplate',
|
||||
'Bake.Test',
|
||||
];
|
||||
|
||||
/**
|
||||
* Get the generated object's name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
abstract public function name();
|
||||
|
||||
/**
|
||||
* Get the generated object's filename without the leading path.
|
||||
*
|
||||
* @param string $name The name of the object being generated
|
||||
* @return string
|
||||
*/
|
||||
abstract public function fileName($name);
|
||||
|
||||
/**
|
||||
* Get the template name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
abstract public function template();
|
||||
|
||||
/**
|
||||
* Get template data.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function templateData()
|
||||
{
|
||||
$namespace = Configure::read('App.namespace');
|
||||
if ($this->plugin) {
|
||||
$namespace = $this->_pluginNamespace($this->plugin);
|
||||
}
|
||||
|
||||
return ['namespace' => $namespace];
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute method
|
||||
*
|
||||
* @param string|null $name The name of the object to bake.
|
||||
* @return int|null
|
||||
*/
|
||||
public function main($name = null)
|
||||
{
|
||||
parent::main();
|
||||
if (empty($name)) {
|
||||
$this->abort('You must provide a name to bake a ' . $this->name());
|
||||
|
||||
return null;
|
||||
}
|
||||
$name = $this->_getName($name);
|
||||
$name = Inflector::camelize($name);
|
||||
$this->bake($name);
|
||||
$this->bakeTest($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a class stub
|
||||
*
|
||||
* @param string $name The classname to generate.
|
||||
* @return string
|
||||
*/
|
||||
public function bake($name)
|
||||
{
|
||||
$this->BakeTemplate->set('name', $name);
|
||||
$this->BakeTemplate->set($this->templateData());
|
||||
$contents = $this->BakeTemplate->generate($this->template());
|
||||
|
||||
$filename = $this->getPath() . $this->fileName($name);
|
||||
$this->createFile($filename, $contents);
|
||||
$emptyFile = $this->getPath() . 'empty';
|
||||
$this->_deleteEmptyFile($emptyFile);
|
||||
|
||||
return $contents;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a test case.
|
||||
*
|
||||
* @param string $className The class to bake a test for.
|
||||
* @return string|bool|null
|
||||
*/
|
||||
public function bakeTest($className)
|
||||
{
|
||||
if (!empty($this->params['no-test'])) {
|
||||
return null;
|
||||
}
|
||||
$this->Test->plugin = $this->plugin;
|
||||
|
||||
return $this->Test->bake($this->name(), $className);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the option parser instance and configures it.
|
||||
*
|
||||
* @return \Cake\Console\ConsoleOptionParser
|
||||
*/
|
||||
public function getOptionParser()
|
||||
{
|
||||
$parser = parent::getOptionParser();
|
||||
$name = $this->name();
|
||||
$parser->setDescription(
|
||||
sprintf('Bake a %s class file.', $name)
|
||||
)->addArgument('name', [
|
||||
'help' => sprintf(
|
||||
'Name of the %s to bake. Can use Plugin.name to bake %s files into plugins.',
|
||||
$name,
|
||||
$name
|
||||
),
|
||||
])->addOption('no-test', [
|
||||
'boolean' => true,
|
||||
'help' => 'Do not generate a test skeleton.',
|
||||
]);
|
||||
|
||||
return $parser;
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 1.2.2
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Bake\Shell\Task;
|
||||
|
||||
/**
|
||||
* Shell Task code generator.
|
||||
*
|
||||
* @property \Bake\Shell\Task\BakeTemplateTask $BakeTemplate
|
||||
* @property \Bake\Shell\Task\TestTask $Test
|
||||
*/
|
||||
class TaskTask extends SimpleBakeTask
|
||||
{
|
||||
/**
|
||||
* Task name used in path generation.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $pathFragment = 'Shell/Task/';
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function name()
|
||||
{
|
||||
return 'task';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function fileName($name)
|
||||
{
|
||||
return $name . 'Task.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function template()
|
||||
{
|
||||
return 'Shell/task';
|
||||
}
|
||||
}
|
||||
+435
@@ -0,0 +1,435 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.1.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Bake\Shell\Task;
|
||||
|
||||
use Bake\Utility\Model\AssociationFilter;
|
||||
use Cake\Console\Shell;
|
||||
use Cake\Core\App;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Datasource\EntityInterface;
|
||||
use Cake\ORM\Table;
|
||||
use Cake\ORM\TableRegistry;
|
||||
use Cake\Utility\Inflector;
|
||||
|
||||
/**
|
||||
* Task class for creating and updating view template files.
|
||||
*
|
||||
* @property \Bake\Shell\Task\ModelTask $Model
|
||||
* @property \Bake\Shell\Task\BakeTemplateTask $BakeTemplate
|
||||
*/
|
||||
class TemplateTask extends BakeTask
|
||||
{
|
||||
/**
|
||||
* Tasks to be loaded by this Task
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $tasks = [
|
||||
'Bake.Model',
|
||||
'Bake.BakeTemplate',
|
||||
];
|
||||
|
||||
/**
|
||||
* path to Template directory
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $pathFragment = 'Template/';
|
||||
|
||||
/**
|
||||
* Name of the controller being used
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $controllerName = null;
|
||||
|
||||
/**
|
||||
* Classname of the controller being used
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $controllerClass = null;
|
||||
|
||||
/**
|
||||
* Name with plugin of the model being used
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $modelName = null;
|
||||
|
||||
/**
|
||||
* Actions to use for scaffolding
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $scaffoldActions = ['index', 'view', 'add', 'edit'];
|
||||
|
||||
/**
|
||||
* AssociationFilter utility
|
||||
*
|
||||
* @var \Bake\Utility\Model\AssociationFilter|null
|
||||
*/
|
||||
protected $_associationFilter = null;
|
||||
|
||||
/**
|
||||
* Template path.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $path;
|
||||
|
||||
/**
|
||||
* Override initialize
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function initialize()
|
||||
{
|
||||
$this->path = current(App::path('Template'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Execution method always used for tasks
|
||||
*
|
||||
* @param string|null $name The name of the controller to bake view templates for.
|
||||
* @param string|null $template The template to bake with.
|
||||
* @param string|null $action The output action name. Defaults to $template.
|
||||
* @return mixed
|
||||
*/
|
||||
public function main($name = null, $template = null, $action = null)
|
||||
{
|
||||
parent::main();
|
||||
|
||||
if (empty($name)) {
|
||||
$this->out('Possible tables to bake view templates for based on your current database:');
|
||||
$this->Model->connection = $this->connection;
|
||||
foreach ($this->Model->listUnskipped() as $table) {
|
||||
$this->out('- ' . $this->_camelize($table));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
$name = $this->_getName($name);
|
||||
|
||||
$controller = null;
|
||||
if (!empty($this->params['controller'])) {
|
||||
$controller = $this->params['controller'];
|
||||
}
|
||||
$this->controller($name, $controller);
|
||||
$this->model($name);
|
||||
|
||||
if ($template && $action === null) {
|
||||
$action = $template;
|
||||
}
|
||||
if ($template) {
|
||||
$this->bake($template, true, $action);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
$vars = $this->_loadController();
|
||||
$methods = $this->_methodsToBake();
|
||||
|
||||
foreach ($methods as $method) {
|
||||
$content = $this->getContent($method, $vars);
|
||||
if ($content) {
|
||||
$this->bake($method, $content);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the model class for the table.
|
||||
*
|
||||
* @param string $table The table/model that is being baked.
|
||||
* @return void
|
||||
*/
|
||||
public function model($table)
|
||||
{
|
||||
$tableName = $this->_camelize($table);
|
||||
$plugin = null;
|
||||
if (!empty($this->params['plugin'])) {
|
||||
$plugin = $this->params['plugin'] . '.';
|
||||
}
|
||||
$this->modelName = $plugin . $tableName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the controller related properties.
|
||||
*
|
||||
* @param string $table The table/model that is being baked.
|
||||
* @param string|null $controller The controller name if specified.
|
||||
* @return void
|
||||
*/
|
||||
public function controller($table, $controller = null)
|
||||
{
|
||||
$tableName = $this->_camelize($table);
|
||||
if (empty($controller)) {
|
||||
$controller = $tableName;
|
||||
}
|
||||
$this->controllerName = $controller;
|
||||
|
||||
$plugin = $this->param('plugin');
|
||||
if ($plugin) {
|
||||
$plugin .= '.';
|
||||
}
|
||||
$prefix = $this->_getPrefix();
|
||||
if ($prefix) {
|
||||
$prefix .= '/';
|
||||
}
|
||||
$this->controllerClass = (string)App::className($plugin . $prefix . $controller, 'Controller', 'Controller');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the path base for view templates.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getPath()
|
||||
{
|
||||
$path = parent::getPath();
|
||||
$path .= $this->controllerName . DS;
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of actions that can / should have view templates baked for them.
|
||||
*
|
||||
* @return array Array of action names that should be baked
|
||||
*/
|
||||
protected function _methodsToBake()
|
||||
{
|
||||
$base = Configure::read('App.namespace');
|
||||
|
||||
$methods = [];
|
||||
if (class_exists($this->controllerClass)) {
|
||||
$methods = array_diff(
|
||||
array_map(
|
||||
'Cake\Utility\Inflector::underscore',
|
||||
get_class_methods($this->controllerClass)
|
||||
),
|
||||
array_map(
|
||||
'Cake\Utility\Inflector::underscore',
|
||||
get_class_methods($base . '\Controller\AppController')
|
||||
)
|
||||
);
|
||||
}
|
||||
if (empty($methods)) {
|
||||
$methods = $this->scaffoldActions;
|
||||
}
|
||||
foreach ($methods as $i => $method) {
|
||||
if ($method[0] === '_') {
|
||||
unset($methods[$i]);
|
||||
}
|
||||
}
|
||||
|
||||
return $methods;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bake All view templates for all controller actions.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function all()
|
||||
{
|
||||
$this->Model->connection = $this->connection;
|
||||
$tables = $this->Model->listUnskipped();
|
||||
|
||||
foreach ($tables as $table) {
|
||||
$this->main($table);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads Controller and sets variables for the template
|
||||
* Available template variables:
|
||||
*
|
||||
* - 'modelObject'
|
||||
* - 'modelClass'
|
||||
* - 'entityClass'
|
||||
* - 'primaryKey'
|
||||
* - 'displayField'
|
||||
* - 'singularVar'
|
||||
* - 'pluralVar'
|
||||
* - 'singularHumanName'
|
||||
* - 'pluralHumanName'
|
||||
* - 'fields'
|
||||
* - 'keyFields'
|
||||
* - 'schema'
|
||||
*
|
||||
* @return array Returns variables to be made available to a view template
|
||||
*/
|
||||
protected function _loadController()
|
||||
{
|
||||
if (TableRegistry::getTableLocator()->exists($this->modelName)) {
|
||||
$modelObject = TableRegistry::getTableLocator()->get($this->modelName);
|
||||
} else {
|
||||
$modelObject = TableRegistry::getTableLocator()->get($this->modelName, [
|
||||
'connectionName' => $this->connection,
|
||||
]);
|
||||
}
|
||||
|
||||
$namespace = Configure::read('App.namespace');
|
||||
|
||||
$primaryKey = (array)$modelObject->getPrimaryKey();
|
||||
$displayField = $modelObject->getDisplayField();
|
||||
$singularVar = $this->_singularName($this->controllerName);
|
||||
$singularHumanName = $this->_singularHumanName($this->controllerName);
|
||||
$schema = $modelObject->getSchema();
|
||||
$fields = $schema->columns();
|
||||
$modelClass = $this->modelName;
|
||||
|
||||
list(, $entityClass) = namespaceSplit($this->_entityName($this->modelName));
|
||||
$entityClass = sprintf('%s\Model\Entity\%s', $namespace, $entityClass);
|
||||
if (!class_exists($entityClass)) {
|
||||
$entityClass = EntityInterface::class;
|
||||
}
|
||||
$associations = $this->_filteredAssociations($modelObject);
|
||||
$keyFields = [];
|
||||
if (!empty($associations['BelongsTo'])) {
|
||||
foreach ($associations['BelongsTo'] as $assoc) {
|
||||
$keyFields[$assoc['foreignKey']] = $assoc['variable'];
|
||||
}
|
||||
}
|
||||
|
||||
$pluralVar = Inflector::variable($this->controllerName);
|
||||
$pluralHumanName = $this->_pluralHumanName($this->controllerName);
|
||||
|
||||
return compact(
|
||||
'modelObject',
|
||||
'modelClass',
|
||||
'entityClass',
|
||||
'schema',
|
||||
'primaryKey',
|
||||
'displayField',
|
||||
'singularVar',
|
||||
'pluralVar',
|
||||
'singularHumanName',
|
||||
'pluralHumanName',
|
||||
'fields',
|
||||
'associations',
|
||||
'keyFields',
|
||||
'namespace'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Assembles and writes bakes the view file.
|
||||
*
|
||||
* @param string $template Template file to use.
|
||||
* @param string|true $content Content to write.
|
||||
* @param string $outputFile The output file to create. If null will use `$template`
|
||||
* @return string|false Generated file content.
|
||||
*/
|
||||
public function bake($template, $content = '', $outputFile = null)
|
||||
{
|
||||
if ($outputFile === null) {
|
||||
$outputFile = $template;
|
||||
}
|
||||
if ($content === true) {
|
||||
$content = $this->getContent($template);
|
||||
}
|
||||
if (empty($content)) {
|
||||
$this->err("<warning>No generated content for '{$template}.ctp', not generating template.</warning>");
|
||||
|
||||
return false;
|
||||
}
|
||||
$this->out("\n" . sprintf('Baking `%s` view template file...', $outputFile), 1, Shell::QUIET);
|
||||
$path = $this->getPath();
|
||||
$filename = $path . Inflector::underscore($outputFile) . '.ctp';
|
||||
$this->createFile($filename, $content);
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds content from template and variables
|
||||
*
|
||||
* @param string $action name to generate content to
|
||||
* @param array|null $vars passed for use in templates
|
||||
* @return string|false Content from template
|
||||
*/
|
||||
public function getContent($action, $vars = null)
|
||||
{
|
||||
if (!$vars) {
|
||||
$vars = $this->_loadController();
|
||||
}
|
||||
|
||||
if (empty($vars['primaryKey'])) {
|
||||
$this->abort('Cannot generate views for models with no primary key');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($action === "index" && !empty($this->params['index-columns'])) {
|
||||
$this->BakeTemplate->set('indexColumns', $this->params['index-columns']);
|
||||
}
|
||||
|
||||
$this->BakeTemplate->set('action', $action);
|
||||
$this->BakeTemplate->set('plugin', $this->plugin);
|
||||
$this->BakeTemplate->set($vars);
|
||||
|
||||
return $this->BakeTemplate->generate("Template/$action");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the option parser instance and configures it.
|
||||
*
|
||||
* @return \Cake\Console\ConsoleOptionParser
|
||||
*/
|
||||
public function getOptionParser()
|
||||
{
|
||||
$parser = parent::getOptionParser();
|
||||
|
||||
$parser->setDescription(
|
||||
'Bake views for a controller, using built-in or custom templates. '
|
||||
)->addArgument('controller', [
|
||||
'help' => 'Name of the controller views to bake. You can use Plugin.name as a shortcut for plugin baking.',
|
||||
])->addArgument('action', [
|
||||
'help' => "Will bake a single action's file. core templates are (index, add, edit, view)",
|
||||
])->addArgument('alias', [
|
||||
'help' => 'Will bake the template in <action> but create the filename after <alias>.',
|
||||
])->addOption('controller', [
|
||||
'help' => 'The controller name if you have a controller that does not follow conventions.',
|
||||
])->addOption('prefix', [
|
||||
'help' => 'The routing prefix to generate views for.',
|
||||
])->addOption('index-columns', [
|
||||
'help' => 'Limit for the number of index columns',
|
||||
'default' => 0,
|
||||
])->addSubcommand('all', [
|
||||
'help' => '[optional] Bake all CRUD action views for all controllers. Requires models and controllers to exist.',
|
||||
]);
|
||||
|
||||
return $parser;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get filtered associations
|
||||
* To be mocked...
|
||||
*
|
||||
* @param \Cake\ORM\Table $model Table
|
||||
* @return array associations
|
||||
*/
|
||||
protected function _filteredAssociations(Table $model)
|
||||
{
|
||||
if (is_null($this->_associationFilter)) {
|
||||
$this->_associationFilter = new AssociationFilter();
|
||||
}
|
||||
|
||||
return $this->_associationFilter->filterAssociations($model);
|
||||
}
|
||||
}
|
||||
+752
@@ -0,0 +1,752 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.1.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
namespace Bake\Shell\Task;
|
||||
|
||||
use Cake\Console\Shell;
|
||||
use Cake\Controller\Controller;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Core\Exception\Exception;
|
||||
use Cake\Core\Plugin;
|
||||
use Cake\Filesystem\Folder;
|
||||
use Cake\Http\Response;
|
||||
use Cake\Http\ServerRequest as Request;
|
||||
use Cake\ORM\Association;
|
||||
use Cake\ORM\Table;
|
||||
use Cake\ORM\TableRegistry;
|
||||
use Cake\Utility\Inflector;
|
||||
use ReflectionClass;
|
||||
|
||||
/**
|
||||
* Task class for creating and updating test files.
|
||||
*
|
||||
* @property \Bake\Shell\Task\BakeTemplateTask $BakeTemplate
|
||||
*/
|
||||
class TestTask extends BakeTask
|
||||
{
|
||||
/**
|
||||
* Tasks used.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $tasks = ['Bake.BakeTemplate'];
|
||||
|
||||
/**
|
||||
* class types that methods can be generated for
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $classTypes = [
|
||||
'Entity' => 'Model\Entity',
|
||||
'Table' => 'Model\Table',
|
||||
'Controller' => 'Controller',
|
||||
'Component' => 'Controller\Component',
|
||||
'Behavior' => 'Model\Behavior',
|
||||
'Helper' => 'View\Helper',
|
||||
'Shell' => 'Shell',
|
||||
'Task' => 'Shell\Task',
|
||||
'ShellHelper' => 'Shell\Helper',
|
||||
'Cell' => 'View\Cell',
|
||||
'Form' => 'Form',
|
||||
'Mailer' => 'Mailer',
|
||||
'Command' => 'Command',
|
||||
];
|
||||
|
||||
/**
|
||||
* class types that methods can be generated for
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $classSuffixes = [
|
||||
'Entity' => '',
|
||||
'Table' => 'Table',
|
||||
'Controller' => 'Controller',
|
||||
'Component' => 'Component',
|
||||
'Behavior' => 'Behavior',
|
||||
'Helper' => 'Helper',
|
||||
'Shell' => 'Shell',
|
||||
'Task' => 'Task',
|
||||
'ShellHelper' => 'Helper',
|
||||
'Cell' => 'Cell',
|
||||
'Form' => 'Form',
|
||||
'Mailer' => 'Mailer',
|
||||
'Command' => 'Command',
|
||||
];
|
||||
|
||||
/**
|
||||
* Internal list of fixtures that have been added so far.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_fixtures = [];
|
||||
|
||||
/**
|
||||
* Execution method always used for tasks
|
||||
*
|
||||
* @param string|null $type Class type.
|
||||
* @param string|null $name Name.
|
||||
* @return array|null
|
||||
*/
|
||||
public function main($type = null, $name = null)
|
||||
{
|
||||
parent::main();
|
||||
$type = $this->normalize($type);
|
||||
$name = $this->_getName($name);
|
||||
|
||||
if (empty($type) && empty($name)) {
|
||||
$this->outputTypeChoices();
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($this->param('all')) {
|
||||
$this->_bakeAll($type);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
if (empty($name)) {
|
||||
return $this->outputClassChoices($type);
|
||||
}
|
||||
|
||||
if ($this->bake($type, $name)) {
|
||||
$this->out('<success>Done</success>');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Output a list of class types you can bake a test for.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function outputTypeChoices()
|
||||
{
|
||||
$this->out(
|
||||
'You must provide a class type to bake a test for. The valid types are:',
|
||||
2
|
||||
);
|
||||
$i = 0;
|
||||
foreach ($this->classTypes as $option => $package) {
|
||||
$this->out(++$i . '. ' . $option);
|
||||
}
|
||||
$this->out('');
|
||||
$this->out('Re-run your command as `cake bake <type> <classname>`');
|
||||
}
|
||||
|
||||
/**
|
||||
* Output a list of possible classnames you might want to generate a test for.
|
||||
*
|
||||
* @param string $typeName The typename to get classes for.
|
||||
* @return array
|
||||
*/
|
||||
public function outputClassChoices($typeName)
|
||||
{
|
||||
$type = $this->mapType($typeName);
|
||||
$this->out(
|
||||
'You must provide a class to bake a test for. Some possible options are:',
|
||||
2
|
||||
);
|
||||
$options = $this->_getClassOptions($type);
|
||||
$i = 0;
|
||||
foreach ($options as $option) {
|
||||
$this->out(++$i . '. ' . $option);
|
||||
}
|
||||
$this->out('');
|
||||
$this->out('Re-run your command as `cake bake ' . $typeName . ' <classname>`');
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $type The typename to get bake all classes for.
|
||||
* @return void
|
||||
*/
|
||||
protected function _bakeAll($type)
|
||||
{
|
||||
$mappedType = $this->mapType($type);
|
||||
$classes = $this->_getClassOptions($mappedType);
|
||||
|
||||
foreach ($classes as $class) {
|
||||
if ($this->bake($type, $class)) {
|
||||
$this->out('<success>Done - ' . $class . '</success>');
|
||||
} else {
|
||||
$this->out('<error>Failed - ' . $class . '</error>');
|
||||
}
|
||||
}
|
||||
|
||||
$this->out('<info>Bake finished</info>');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the possible classes for a given type.
|
||||
*
|
||||
* @param string $namespace The namespace fragment to look for classes in.
|
||||
* @return array
|
||||
*/
|
||||
protected function _getClassOptions($namespace)
|
||||
{
|
||||
$classes = [];
|
||||
$base = APP;
|
||||
if ($this->plugin) {
|
||||
$base = Plugin::classPath($this->plugin);
|
||||
}
|
||||
$path = $base . str_replace('\\', DS, $namespace);
|
||||
$folder = new Folder($path);
|
||||
list(, $files) = $folder->read();
|
||||
foreach ($files as $file) {
|
||||
$classes[] = str_replace('.php', '', $file);
|
||||
}
|
||||
|
||||
return $classes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Completes final steps for generating data to create test case.
|
||||
*
|
||||
* @param string $type Type of object to bake test case for ie. Model, Controller
|
||||
* @param string $className the 'cake name' for the class ie. Posts for the PostsController
|
||||
* @return string|false
|
||||
*/
|
||||
public function bake($type, $className)
|
||||
{
|
||||
$type = $this->normalize($type);
|
||||
if (!isset($this->classSuffixes[$type]) || !isset($this->classTypes[$type])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$fullClassName = $this->getRealClassName($type, $className);
|
||||
|
||||
if (empty($this->params['no-fixture'])) {
|
||||
if (!empty($this->params['fixtures'])) {
|
||||
$fixtures = array_map('trim', explode(',', $this->params['fixtures']));
|
||||
$this->_fixtures = array_filter($fixtures);
|
||||
} elseif ($this->typeCanDetectFixtures($type) && class_exists($fullClassName)) {
|
||||
$this->out('Bake is detecting possible fixtures...');
|
||||
$testSubject = $this->buildTestSubject($type, $fullClassName);
|
||||
$this->generateFixtureList($testSubject);
|
||||
}
|
||||
}
|
||||
|
||||
$methods = [];
|
||||
if (class_exists($fullClassName)) {
|
||||
$methods = $this->getTestableMethods($fullClassName);
|
||||
}
|
||||
$mock = $this->hasMockClass($type);
|
||||
list($preConstruct, $construction, $postConstruct) = $this->generateConstructor($type, $fullClassName);
|
||||
$uses = $this->generateUses($type, $fullClassName);
|
||||
|
||||
$subject = $className;
|
||||
list($namespace, $className) = namespaceSplit($fullClassName);
|
||||
|
||||
$baseNamespace = Configure::read('App.namespace');
|
||||
if ($this->plugin) {
|
||||
$baseNamespace = $this->_pluginNamespace($this->plugin);
|
||||
}
|
||||
$subNamespace = substr($namespace, strlen($baseNamespace) + 1);
|
||||
|
||||
$properties = $this->generateProperties($type, $subject, $fullClassName);
|
||||
|
||||
$this->out("\n" . sprintf('Baking test case for %s ...', $fullClassName), 1, Shell::QUIET);
|
||||
|
||||
$this->BakeTemplate->set('fixtures', $this->_fixtures);
|
||||
$this->BakeTemplate->set('plugin', $this->plugin);
|
||||
$this->BakeTemplate->set(compact(
|
||||
'subject',
|
||||
'className',
|
||||
'properties',
|
||||
'methods',
|
||||
'type',
|
||||
'fullClassName',
|
||||
'mock',
|
||||
'type',
|
||||
'preConstruct',
|
||||
'postConstruct',
|
||||
'construction',
|
||||
'uses',
|
||||
'baseNamespace',
|
||||
'subNamespace',
|
||||
'namespace'
|
||||
));
|
||||
$out = $this->BakeTemplate->generate('tests/test_case');
|
||||
|
||||
$filename = $this->testCaseFileName($type, $fullClassName);
|
||||
$emptyFile = $this->getPath() . $this->getSubspacePath($type) . DS . 'empty';
|
||||
$this->_deleteEmptyFile($emptyFile);
|
||||
if ($this->createFile($filename, $out)) {
|
||||
return $out;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the chosen type can find its own fixtures.
|
||||
* Currently only model, and controller are supported
|
||||
*
|
||||
* @param string $type The Type of object you are generating tests for eg. controller
|
||||
* @return bool
|
||||
*/
|
||||
public function typeCanDetectFixtures($type)
|
||||
{
|
||||
return in_array($type, ['Controller', 'Table'], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct an instance of the class to be tested.
|
||||
* So that fixtures can be detected
|
||||
*
|
||||
* @param string $type The type of object you are generating tests for eg. controller
|
||||
* @param string $class The classname of the class the test is being generated for.
|
||||
* @return object And instance of the class that is going to be tested.
|
||||
*/
|
||||
public function buildTestSubject($type, $class)
|
||||
{
|
||||
if ($type === 'Table') {
|
||||
list(, $name) = namespaceSplit($class);
|
||||
$name = str_replace('Table', '', $name);
|
||||
if ($this->plugin) {
|
||||
$name = $this->plugin . '.' . $name;
|
||||
}
|
||||
if (TableRegistry::getTableLocator()->exists($name)) {
|
||||
$instance = TableRegistry::getTableLocator()->get($name);
|
||||
} else {
|
||||
$instance = TableRegistry::getTableLocator()->get($name, [
|
||||
'connectionName' => $this->connection,
|
||||
]);
|
||||
}
|
||||
} elseif ($type === 'Controller') {
|
||||
$instance = new $class(new Request(), new Response());
|
||||
} else {
|
||||
$instance = new $class();
|
||||
}
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the real class name from the cake short form. If the class name is already
|
||||
* suffixed with the type, the type will not be duplicated.
|
||||
*
|
||||
* @param string $type The Type of object you are generating tests for eg. controller.
|
||||
* @param string $class the Classname of the class the test is being generated for.
|
||||
* @return string Real class name
|
||||
*/
|
||||
public function getRealClassName($type, $class)
|
||||
{
|
||||
$namespace = Configure::read('App.namespace');
|
||||
if ($this->plugin) {
|
||||
$namespace = str_replace('/', '\\', $this->plugin);
|
||||
}
|
||||
$suffix = $this->classSuffixes[$type];
|
||||
$subSpace = $this->mapType($type);
|
||||
if ($suffix && strpos($class, $suffix) === false) {
|
||||
$class .= $suffix;
|
||||
}
|
||||
$prefix = $this->_getPrefix();
|
||||
if (in_array($type, ['Controller', 'Cell'], true) && $prefix) {
|
||||
$subSpace .= '\\' . str_replace('/', '\\', $prefix);
|
||||
}
|
||||
|
||||
return $namespace . '\\' . $subSpace . '\\' . $class;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the subspace path for a test.
|
||||
*
|
||||
* @param string $type The Type of object you are generating tests for eg. controller.
|
||||
* @return string Path of the subspace.
|
||||
*/
|
||||
public function getSubspacePath($type)
|
||||
{
|
||||
$subspace = $this->mapType($type);
|
||||
|
||||
return str_replace('\\', DS, $subspace);
|
||||
}
|
||||
|
||||
/**
|
||||
* Map the types that TestTask uses to concrete types that App::className can use.
|
||||
*
|
||||
* @param string $type The type of thing having a test generated.
|
||||
* @return string
|
||||
* @throws \Cake\Core\Exception\Exception When invalid object types are requested.
|
||||
*/
|
||||
public function mapType($type)
|
||||
{
|
||||
if (empty($this->classTypes[$type])) {
|
||||
throw new Exception('Invalid object type.');
|
||||
}
|
||||
|
||||
return $this->classTypes[$type];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get methods declared in the class given.
|
||||
* No parent methods will be returned
|
||||
*
|
||||
* @param string $className Name of class to look at.
|
||||
* @return array Array of method names.
|
||||
*/
|
||||
public function getTestableMethods($className)
|
||||
{
|
||||
$class = new ReflectionClass($className);
|
||||
$out = [];
|
||||
foreach ($class->getMethods() as $method) {
|
||||
if ($method->getDeclaringClass()->getName() !== $className) {
|
||||
continue;
|
||||
}
|
||||
if (!$method->isPublic()) {
|
||||
continue;
|
||||
}
|
||||
$out[] = $method->getName();
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate the list of fixtures that will be required to run this test based on
|
||||
* loaded models.
|
||||
*
|
||||
* @param object $subject The object you want to generate fixtures for.
|
||||
* @return array Array of fixtures to be included in the test.
|
||||
*/
|
||||
public function generateFixtureList($subject)
|
||||
{
|
||||
$this->_fixtures = [];
|
||||
if ($subject instanceof Table) {
|
||||
$this->_processModel($subject);
|
||||
} elseif ($subject instanceof Controller) {
|
||||
$this->_processController($subject);
|
||||
}
|
||||
|
||||
return array_values($this->_fixtures);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a model, pull out model name + associations converted to fixture names.
|
||||
*
|
||||
* @param \Cake\ORM\Table $subject A Model class to scan for associations and pull fixtures off of.
|
||||
* @return void
|
||||
*/
|
||||
protected function _processModel($subject)
|
||||
{
|
||||
if (!$subject instanceof Table) {
|
||||
return;
|
||||
}
|
||||
$this->_addFixture($subject->getAlias());
|
||||
foreach ($subject->associations()->keys() as $alias) {
|
||||
$assoc = $subject->getAssociation($alias);
|
||||
$target = $assoc->getTarget();
|
||||
$name = $target->getAlias();
|
||||
$subjectClass = get_class($subject);
|
||||
|
||||
if ($subjectClass !== 'Cake\ORM\Table' && $subjectClass === get_class($target)) {
|
||||
continue;
|
||||
}
|
||||
if (!isset($this->_fixtures[$name])) {
|
||||
$this->_addFixture($target->getAlias());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process all the models attached to a controller
|
||||
* and generate a fixture list.
|
||||
*
|
||||
* @param \Cake\Controller\Controller $subject A controller to pull model names off of.
|
||||
* @return void
|
||||
*/
|
||||
protected function _processController($subject)
|
||||
{
|
||||
$models = [$subject->modelClass];
|
||||
foreach ($models as $model) {
|
||||
list(, $model) = pluginSplit($model);
|
||||
$this->_processModel($subject->{$model});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add class name to the fixture list.
|
||||
* Sets the app. or plugin.plugin_name. prefix.
|
||||
*
|
||||
* @param string $name Name of the Model class that a fixture might be required for.
|
||||
* @return void
|
||||
*/
|
||||
protected function _addFixture($name)
|
||||
{
|
||||
if ($this->plugin) {
|
||||
$prefix = 'plugin.' . $this->plugin . '.';
|
||||
} else {
|
||||
$prefix = 'app.';
|
||||
}
|
||||
$fixture = $prefix . $this->_fixtureName($name);
|
||||
$this->_fixtures[$name] = $fixture;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is a mock class required for this type of test?
|
||||
* Controllers require a mock class.
|
||||
*
|
||||
* @param string $type The type of object tests are being generated for eg. controller.
|
||||
* @return bool
|
||||
*/
|
||||
public function hasMockClass($type)
|
||||
{
|
||||
return $type === 'Controller';
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a constructor code snippet for the type and class name
|
||||
*
|
||||
* @param string $type The Type of object you are generating tests for eg. controller
|
||||
* @param string $fullClassName The full classname of the class the test is being generated for.
|
||||
* @return array Constructor snippets for the thing you are building.
|
||||
*/
|
||||
public function generateConstructor($type, $fullClassName)
|
||||
{
|
||||
list(, $className) = namespaceSplit($fullClassName);
|
||||
$pre = $construct = $post = '';
|
||||
if ($type === 'Table') {
|
||||
$tableName = str_replace('Table', '', $className);
|
||||
$pre = "\$config = TableRegistry::getTableLocator()->exists('{$tableName}') ? [] : ['className' => {$className}::class];";
|
||||
$construct = "TableRegistry::getTableLocator()->get('{$tableName}', \$config);";
|
||||
}
|
||||
if ($type === 'Behavior' || $type === 'Entity' || $type === 'Form') {
|
||||
$construct = "new {$className}();";
|
||||
}
|
||||
if ($type === 'Helper') {
|
||||
$pre = "\$view = new View();";
|
||||
$construct = "new {$className}(\$view);";
|
||||
}
|
||||
if ($type === 'Command') {
|
||||
$construct = "\$this->useCommandRunner();";
|
||||
}
|
||||
if ($type === 'Component') {
|
||||
$pre = "\$registry = new ComponentRegistry();";
|
||||
$construct = "new {$className}(\$registry);";
|
||||
}
|
||||
if ($type === 'Shell') {
|
||||
$pre = "\$this->io = \$this->getMockBuilder('Cake\Console\ConsoleIo')->getMock();";
|
||||
$construct = "new {$className}(\$this->io);";
|
||||
}
|
||||
if ($type === 'Task') {
|
||||
$pre = "\$this->io = \$this->getMockBuilder('Cake\Console\ConsoleIo')->getMock();";
|
||||
$construct = "new {$className}(\$this->io);";
|
||||
}
|
||||
if ($type === 'Cell') {
|
||||
$pre = "\$this->request = \$this->getMockBuilder('Cake\Http\ServerRequest')->getMock();\n";
|
||||
$pre .= " \$this->response = \$this->getMockBuilder('Cake\Http\Response')->getMock();";
|
||||
$construct = "new {$className}(\$this->request, \$this->response);";
|
||||
}
|
||||
if ($type === 'ShellHelper') {
|
||||
$pre = "\$this->stub = new ConsoleOutput();\n";
|
||||
$pre .= " \$this->io = new ConsoleIo(\$this->stub);";
|
||||
$construct = "new {$className}(\$this->io);";
|
||||
}
|
||||
|
||||
return [$pre, $construct, $post];
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate property info for the type and class name
|
||||
*
|
||||
* The generated property info consists of a set of arrays that hold the following keys:
|
||||
*
|
||||
* - `description` (the property description)
|
||||
* - `type` (the property docblock type)
|
||||
* - `name` (the property name)
|
||||
* - `value` (optional - the properties initial value)
|
||||
*
|
||||
* @param string $type The Type of object you are generating tests for eg. controller
|
||||
* @param string $subject The name of the test subject.
|
||||
* @param string $fullClassName The Classname of the class the test is being generated for.
|
||||
* @return array An array containing property info
|
||||
*/
|
||||
public function generateProperties($type, $subject, $fullClassName)
|
||||
{
|
||||
$properties = [];
|
||||
switch ($type) {
|
||||
case 'Cell':
|
||||
$properties[] = [
|
||||
'description' => 'Request mock',
|
||||
'type' => '\Cake\Http\ServerRequest|\PHPUnit_Framework_MockObject_MockObject',
|
||||
'name' => 'request',
|
||||
];
|
||||
$properties[] = [
|
||||
'description' => 'Response mock',
|
||||
'type' => '\Cake\Http\Response|\PHPUnit_Framework_MockObject_MockObject',
|
||||
'name' => 'response',
|
||||
];
|
||||
break;
|
||||
|
||||
case 'Shell':
|
||||
case 'Task':
|
||||
$properties[] = [
|
||||
'description' => 'ConsoleIo mock',
|
||||
'type' => '\Cake\Console\ConsoleIo|\PHPUnit_Framework_MockObject_MockObject',
|
||||
'name' => 'io',
|
||||
];
|
||||
break;
|
||||
|
||||
case 'ShellHelper':
|
||||
$properties[] = [
|
||||
'description' => 'ConsoleOutput stub',
|
||||
'type' => '\Cake\TestSuite\Stub\ConsoleOutput',
|
||||
'name' => 'stub',
|
||||
];
|
||||
$properties[] = [
|
||||
'description' => 'ConsoleIo mock',
|
||||
'type' => '\Cake\Console\ConsoleIo',
|
||||
'name' => 'io',
|
||||
];
|
||||
break;
|
||||
}
|
||||
|
||||
if (!in_array($type, ['Controller', 'Command'])) {
|
||||
$properties[] = [
|
||||
'description' => 'Test subject',
|
||||
'type' => '\\' . $fullClassName,
|
||||
'name' => $subject,
|
||||
];
|
||||
}
|
||||
|
||||
return $properties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate the uses() calls for a type & class name
|
||||
*
|
||||
* @param string $type The Type of object you are generating tests for eg. controller
|
||||
* @param string $fullClassName The Classname of the class the test is being generated for.
|
||||
* @return array An array containing used classes
|
||||
*/
|
||||
public function generateUses($type, $fullClassName)
|
||||
{
|
||||
$uses = [];
|
||||
if ($type === 'Component') {
|
||||
$uses[] = 'Cake\Controller\ComponentRegistry';
|
||||
}
|
||||
if ($type === 'Table') {
|
||||
$uses[] = 'Cake\ORM\TableRegistry';
|
||||
}
|
||||
if ($type === 'Helper') {
|
||||
$uses[] = 'Cake\View\View';
|
||||
}
|
||||
if ($type === 'ShellHelper') {
|
||||
$uses[] = 'Cake\TestSuite\Stub\ConsoleOutput';
|
||||
$uses[] = 'Cake\Console\ConsoleIo';
|
||||
}
|
||||
$uses[] = $fullClassName;
|
||||
|
||||
return $uses;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the file path.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getPath()
|
||||
{
|
||||
$dir = 'TestCase/';
|
||||
$path = defined('TESTS') ? TESTS . $dir : ROOT . DS . 'tests' . DS . $dir;
|
||||
if (isset($this->plugin)) {
|
||||
$path = $this->_pluginPath($this->plugin) . 'tests/' . $dir;
|
||||
}
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make the filename for the test case. resolve the suffixes for controllers
|
||||
* and get the plugin path if needed.
|
||||
*
|
||||
* @param string $type The Type of object you are generating tests for eg. controller
|
||||
* @param string $className The fully qualified classname of the class the test is being generated for.
|
||||
* @return string filename the test should be created on.
|
||||
*/
|
||||
public function testCaseFileName($type, $className)
|
||||
{
|
||||
$path = $this->getPath();
|
||||
$namespace = Configure::read('App.namespace');
|
||||
if ($this->plugin) {
|
||||
$namespace = $this->plugin;
|
||||
}
|
||||
|
||||
$classTail = substr($className, strlen($namespace) + 1);
|
||||
$path = $path . $classTail . 'Test.php';
|
||||
|
||||
return str_replace(['/', '\\'], DS, $path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the option parser instance and configures it.
|
||||
*
|
||||
* @return \Cake\Console\ConsoleOptionParser
|
||||
*/
|
||||
public function getOptionParser()
|
||||
{
|
||||
$parser = parent::getOptionParser();
|
||||
|
||||
$types = array_keys($this->classTypes);
|
||||
$types = array_merge($types, array_map([$this, 'underscore'], $types));
|
||||
|
||||
$parser->setDescription(
|
||||
'Bake test case skeletons for classes.'
|
||||
)->addArgument('type', [
|
||||
'help' => 'Type of class to bake, can be any of the following:' .
|
||||
' controller, model, helper, component or behavior.',
|
||||
'choices' => $types,
|
||||
])->addArgument('name', [
|
||||
'help' => 'An existing class to bake tests for.',
|
||||
])->addOption('fixtures', [
|
||||
'help' => 'A comma separated list of fixture names you want to include.',
|
||||
])->addOption('no-fixture', [
|
||||
'boolean' => true,
|
||||
'default' => false,
|
||||
'help' => 'Select if you want to bake without fixture.',
|
||||
])->addOption('prefix', [
|
||||
'default' => false,
|
||||
'help' => 'Use when baking tests for prefixed controllers.',
|
||||
])->addOption('all', [
|
||||
'boolean' => true,
|
||||
'help' => 'Bake all classes of the given type',
|
||||
]);
|
||||
|
||||
return $parser;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes string into CamelCase format.
|
||||
*
|
||||
* @param string $string String to inflect
|
||||
* @return string
|
||||
*/
|
||||
protected function normalize($string)
|
||||
{
|
||||
return Inflector::camelize(Inflector::underscore($string));
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to allow under_score format for CLI env usage.
|
||||
*
|
||||
* @param string $string String to inflect
|
||||
* @return string
|
||||
*/
|
||||
protected function underscore($string)
|
||||
{
|
||||
return Inflector::underscore($string);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 1.7.4
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?php
|
||||
namespace {{ namespace }}\Command;
|
||||
|
||||
use Cake\Console\Arguments;
|
||||
use Cake\Console\Command;
|
||||
use Cake\Console\ConsoleIo;
|
||||
use Cake\Console\ConsoleOptionParser;
|
||||
|
||||
/**
|
||||
* {{ name }} command.
|
||||
*/
|
||||
class {{ name }}Command extends Command
|
||||
{
|
||||
/**
|
||||
* Hook method for defining this command's option parser.
|
||||
*
|
||||
* @see https://book.cakephp.org/3.0/en/console-and-shells/commands.html#defining-arguments-and-options
|
||||
*
|
||||
* @param \Cake\Console\ConsoleOptionParser $parser The parser to be defined
|
||||
* @return \Cake\Console\ConsoleOptionParser The built parser.
|
||||
*/
|
||||
public function buildOptionParser(ConsoleOptionParser $parser)
|
||||
{
|
||||
$parser = parent::buildOptionParser($parser);
|
||||
|
||||
return $parser;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implement this method with your command's logic.
|
||||
*
|
||||
* @param \Cake\Console\Arguments $args The command arguments.
|
||||
* @param \Cake\Console\ConsoleIo $io The console io
|
||||
* @return null|int The exit code or null for success
|
||||
*/
|
||||
public function execute(Arguments $args, ConsoleIo $io)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?php
|
||||
namespace {{ namespace }}\Controller\Component;
|
||||
|
||||
use Cake\Controller\Component;
|
||||
use Cake\Controller\ComponentRegistry;
|
||||
|
||||
/**
|
||||
* {{ name }} component
|
||||
*/
|
||||
class {{ name }}Component extends Component
|
||||
{
|
||||
/**
|
||||
* Default configuration.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_defaultConfig = [];
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
{#
|
||||
/**
|
||||
* Controller bake template file
|
||||
*
|
||||
* Allows templating of Controllers generated from bake.
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?php
|
||||
namespace {{ namespace }}\Controller{{ prefix }};
|
||||
|
||||
use {{ namespace }}\Controller\AppController;
|
||||
|
||||
/**
|
||||
* {{ name }} Controller
|
||||
*
|
||||
{% if defaultModel %}
|
||||
* @property \{{ defaultModel }} ${{ name }}
|
||||
{% endif %}
|
||||
|
||||
{%- for component in components %}
|
||||
{% set classInfo = Bake.classInfo(component, 'Controller/Component', 'Component') %}
|
||||
* @property {{ classInfo.fqn }} ${{ classInfo.name }}
|
||||
{% endfor %}
|
||||
|
||||
{%- if 'index' in actions %}
|
||||
*
|
||||
* @method \{{ namespace }}\Model\Entity\{{ entityClassName }}[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
|
||||
{% endif %}
|
||||
*/
|
||||
class {{ name }}Controller extends AppController
|
||||
{
|
||||
{% set helpers = Bake.arrayProperty('helpers', helpers, {'indent': false})|raw %}
|
||||
{% if helpers|trim %}
|
||||
{{- helpers|raw }}
|
||||
{% if components %}
|
||||
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{%- set components = Bake.arrayProperty('components', components, {'indent': false})|raw %}
|
||||
{% if components|trim %}
|
||||
{{- components|raw }}
|
||||
{% if actions %}
|
||||
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{%- for action in actions %}
|
||||
{% if loop.index > 1 %}
|
||||
|
||||
{% endif %}
|
||||
{%- element 'Controller/' ~ action %}
|
||||
{% endfor %}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
{% set compact = ["'#{singularName}'"] %}
|
||||
/**
|
||||
* Add method
|
||||
*
|
||||
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
|
||||
*/
|
||||
public function add()
|
||||
{
|
||||
${{ singularName }} = $this->{{ currentModelName }}->newEntity();
|
||||
if ($this->request->is('post')) {
|
||||
${{ singularName }} = $this->{{ currentModelName }}->patchEntity(${{ singularName }}, $this->request->getData());
|
||||
if ($this->{{ currentModelName }}->save(${{ singularName }})) {
|
||||
$this->Flash->success(__('The {{ singularHumanName|lower }} has been saved.'));
|
||||
|
||||
return $this->redirect(['action' => 'index']);
|
||||
}
|
||||
$this->Flash->error(__('The {{ singularHumanName|lower }} could not be saved. Please, try again.'));
|
||||
}
|
||||
{% set associations = Bake.aliasExtractor(modelObj, 'BelongsTo') %}
|
||||
{% set associations = associations|merge(Bake.aliasExtractor(modelObj, 'BelongsToMany')) %}
|
||||
|
||||
{%- for assoc in associations %}
|
||||
{%- set otherName = Bake.getAssociatedTableAlias(modelObj, assoc) %}
|
||||
{%- set otherPlural = otherName|variable %}
|
||||
${{ otherPlural }} = $this->{{ currentModelName }}->{{ otherName }}->find('list', ['limit' => 200]);
|
||||
{{- "\n" }}
|
||||
{%- set compact = compact|merge(["'#{otherPlural}'"]) %}
|
||||
{% endfor %}
|
||||
$this->set(compact({{ compact|join(', ')|raw }}));
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
/**
|
||||
* Delete method
|
||||
*
|
||||
* @param string|null $id {{ singularHumanName }} id.
|
||||
* @return \Cake\Http\Response|null Redirects to index.
|
||||
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
|
||||
*/
|
||||
public function delete($id = null)
|
||||
{
|
||||
$this->request->allowMethod(['post', 'delete']);
|
||||
${{ singularName }} = $this->{{ currentModelName }}->get($id);
|
||||
if ($this->{{ currentModelName }}->delete(${{ singularName }})) {
|
||||
$this->Flash->success(__('The {{ singularHumanName|lower }} has been deleted.'));
|
||||
} else {
|
||||
$this->Flash->error(__('The {{ singularHumanName|lower }} could not be deleted. Please, try again.'));
|
||||
}
|
||||
|
||||
return $this->redirect(['action' => 'index']);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
{% set belongsTo = Bake.aliasExtractor(modelObj, 'BelongsTo') %}
|
||||
{% set belongsToMany = Bake.aliasExtractor(modelObj, 'belongsToMany') %}
|
||||
{% set compact = ["'#{singularName}'"] %}
|
||||
/**
|
||||
* Edit method
|
||||
*
|
||||
* @param string|null $id {{ singularHumanName }} id.
|
||||
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
|
||||
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
|
||||
*/
|
||||
public function edit($id = null)
|
||||
{
|
||||
${{ singularName }} = $this->{{ currentModelName }}->get($id, [
|
||||
'contain' => [{{ Bake.stringifyList(belongsToMany, {'indent': false})|raw }}],
|
||||
]);
|
||||
if ($this->request->is(['patch', 'post', 'put'])) {
|
||||
${{ singularName }} = $this->{{ currentModelName }}->patchEntity(${{ singularName }}, $this->request->getData());
|
||||
if ($this->{{ currentModelName }}->save(${{ singularName }})) {
|
||||
$this->Flash->success(__('The {{ singularHumanName|lower }} has been saved.'));
|
||||
|
||||
return $this->redirect(['action' => 'index']);
|
||||
}
|
||||
$this->Flash->error(__('The {{ singularHumanName|lower }} could not be saved. Please, try again.'));
|
||||
}
|
||||
{% for assoc in belongsTo|merge(belongsToMany) %}
|
||||
{%- set otherName = Bake.getAssociatedTableAlias(modelObj, assoc) %}
|
||||
{%- set otherPlural = otherName|variable %}
|
||||
${{ otherPlural }} = $this->{{ currentModelName }}->{{ otherName }}->find('list', ['limit' => 200]);
|
||||
{{- "\n" }}
|
||||
{%- set compact = compact|merge(["'#{otherPlural}'"]) %}
|
||||
{% endfor %}
|
||||
$this->set(compact({{ compact|join(', ')|raw }}));
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
/**
|
||||
* Index method
|
||||
*
|
||||
* @return \Cake\Http\Response|null
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
{% set belongsTo = Bake.aliasExtractor(modelObj, 'BelongsTo') %}
|
||||
{% if belongsTo %}
|
||||
$this->paginate = [
|
||||
'contain' => [{{ Bake.stringifyList(belongsTo, {'indent': false})|raw }}],
|
||||
];
|
||||
{% endif %}
|
||||
${{ pluralName }} = $this->paginate($this->{{ currentModelName }});
|
||||
|
||||
$this->set(compact('{{ pluralName }}'));
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
/**
|
||||
* Login method
|
||||
*
|
||||
* @return \Cake\Http\Response|null
|
||||
*/
|
||||
public function login()
|
||||
{
|
||||
if ($this->request->is('post')) {
|
||||
$user = $this->Auth->identify();
|
||||
if ($user) {
|
||||
$this->Auth->setUser($user);
|
||||
|
||||
return $this->redirect($this->Auth->redirectUrl());
|
||||
}
|
||||
$this->Flash->error(__('Invalid credentials, try again'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
/**
|
||||
* Logout method
|
||||
*
|
||||
* @return \Cake\Http\Response
|
||||
*/
|
||||
public function logout()
|
||||
{
|
||||
return $this->redirect($this->Auth->logout());
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
{% set allAssociations = Bake.aliasExtractor(modelObj, 'BelongsTo') %}
|
||||
{% set allAssociations = allAssociations|merge(Bake.aliasExtractor(modelObj, 'BelongsToMany')) %}
|
||||
{% set allAssociations = allAssociations|merge(Bake.aliasExtractor(modelObj, 'HasOne')) %}
|
||||
{% set allAssociations = allAssociations|merge(Bake.aliasExtractor(modelObj, 'HasMany')) %}
|
||||
/**
|
||||
* View method
|
||||
*
|
||||
* @param string|null $id {{ singularHumanName }} id.
|
||||
* @return \Cake\Http\Response|null
|
||||
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
|
||||
*/
|
||||
public function view($id = null)
|
||||
{
|
||||
${{ singularName }} = $this->{{ currentModelName }}->get($id, [
|
||||
'contain' => [{{ Bake.stringifyList(allAssociations, {'indent': false})|raw }}],
|
||||
]);
|
||||
|
||||
$this->set('{{ singularName }}', ${{ singularName }});
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
/**
|
||||
* {{ name|humanize }}
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public ${{ name }} = [{{ Bake.stringifyList(value, {'indent': false})|raw }}];
|
||||
@@ -0,0 +1,80 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
{% set fields = Bake.filterFields(fields, schema, modelObject) %}
|
||||
<nav class="large-3 medium-4 columns" id="actions-sidebar">
|
||||
<ul class="side-nav">
|
||||
<li class="heading"><?= __('Actions') ?></li>
|
||||
{% if strpos(action, 'add') is same as(false) %}
|
||||
<li><?= $this->Form->postLink(
|
||||
__('Delete'),
|
||||
['action' => 'delete', ${{ singularVar }}->{{ primaryKey[0] }}],
|
||||
['confirm' => __('Are you sure you want to delete # {0}?', ${{ singularVar }}->{{ primaryKey[0] }})]
|
||||
)
|
||||
?></li>
|
||||
{% endif %}
|
||||
<li><?= $this->Html->link(__('List {{ pluralHumanName }}'), ['action' => 'index']) ?></li>
|
||||
{{- "\n" }}
|
||||
{%- set done = [] %}
|
||||
{% for type, data in associations %}
|
||||
{%- for alias, details in data %}
|
||||
{%- if details.controller is not same as(_view.name) and details.controller not in done %}
|
||||
<li><?= $this->Html->link(__('List {{ alias|underscore|humanize }}'), ['controller' => '{{ details.controller }}', 'action' => 'index']) ?></li>
|
||||
<li><?= $this->Html->link(__('New {{ alias|singularize|underscore|humanize }}'), ['controller' => '{{ details.controller }}', 'action' => 'add']) ?></li>
|
||||
{{- "\n" }}
|
||||
{%- set done = done|merge([details.controller]) %}
|
||||
{%- endif %}
|
||||
{%- endfor %}
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</nav>
|
||||
<div class="{{ pluralVar }} form large-9 medium-8 columns content">
|
||||
<?= $this->Form->create(${{ singularVar }}) ?>
|
||||
<fieldset>
|
||||
<legend><?= __('{{ action|humanize }} {{ singularHumanName }}') ?></legend>
|
||||
<?php
|
||||
{% for field in fields if field not in primaryKey %}
|
||||
{%- if keyFields[field] %}
|
||||
{%- set fieldData = Bake.columnData(field, schema) %}
|
||||
{%- if fieldData.null %}
|
||||
echo $this->Form->control('{{ field }}', ['options' => ${{ keyFields[field] }}, 'empty' => true]);
|
||||
{{- "\n" }}
|
||||
{%- else %}
|
||||
echo $this->Form->control('{{ field }}', ['options' => ${{ keyFields[field] }}]);
|
||||
{{- "\n" }}
|
||||
{%- endif %}
|
||||
{%- elseif field not in ['created', 'modified', 'updated'] %}
|
||||
{%- set fieldData = Bake.columnData(field, schema) %}
|
||||
{%- if fieldData.type in ['date', 'datetime', 'time'] and fieldData.null %}
|
||||
echo $this->Form->control('{{ field }}', ['empty' => true]);
|
||||
{{- "\n" }}
|
||||
{%- else %}
|
||||
echo $this->Form->control('{{ field }}');
|
||||
{{- "\n" }}
|
||||
{%- endif %}
|
||||
{%- endif %}
|
||||
{%- endfor %}
|
||||
|
||||
{%- if associations.BelongsToMany %}
|
||||
{%- for assocName, assocData in associations.BelongsToMany %}
|
||||
echo $this->Form->control('{{ assocData.property }}._ids', ['options' => ${{ assocData.variable }}]);
|
||||
{{- "\n" }}
|
||||
{%- endfor %}
|
||||
{% endif %}
|
||||
?>
|
||||
</fieldset>
|
||||
<?= $this->Form->button(__('Submit')) ?>
|
||||
<?= $this->Form->end() ?>
|
||||
</div>
|
||||
@@ -0,0 +1,60 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?php
|
||||
namespace {{ namespace }}\Form;
|
||||
|
||||
use Cake\Form\Form;
|
||||
use Cake\Form\Schema;
|
||||
use Cake\Validation\Validator;
|
||||
|
||||
/**
|
||||
* {{ name }} Form.
|
||||
*/
|
||||
class {{ name }}Form extends Form
|
||||
{
|
||||
/**
|
||||
* Builds the schema for the modelless form
|
||||
*
|
||||
* @param \Cake\Form\Schema $schema From schema
|
||||
* @return \Cake\Form\Schema
|
||||
*/
|
||||
protected function _buildSchema(Schema $schema)
|
||||
{
|
||||
return $schema;
|
||||
}
|
||||
|
||||
/**
|
||||
* Form validation builder
|
||||
*
|
||||
* @param \Cake\Validation\Validator $validator to use against the form
|
||||
* @return \Cake\Validation\Validator
|
||||
*/
|
||||
protected function _buildValidator(Validator $validator)
|
||||
{
|
||||
return $validator;
|
||||
}
|
||||
|
||||
/**
|
||||
* Defines what to execute once the Form is processed
|
||||
*
|
||||
* @param array $data Form data.
|
||||
* @return bool
|
||||
*/
|
||||
protected function _execute(array $data)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
{{ _view.fetch('content')|raw }}
|
||||
@@ -0,0 +1,32 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?php
|
||||
namespace {{ namespace }}\Mailer;
|
||||
|
||||
use Cake\Mailer\Mailer;
|
||||
|
||||
/**
|
||||
* {{ name }} mailer.
|
||||
*/
|
||||
class {{ name }}Mailer extends Mailer
|
||||
{
|
||||
/**
|
||||
* Mailer's name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public static $name = '{{ name }}';
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?php
|
||||
namespace {{namespace }}\Middleware;
|
||||
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
|
||||
/**
|
||||
* {{ name }} middleware
|
||||
*/
|
||||
class {{ name }}Middleware
|
||||
{
|
||||
/**
|
||||
* Invoke method.
|
||||
*
|
||||
* @param \Psr\Http\Message\ServerRequestInterface $request The request.
|
||||
* @param \Psr\Http\Message\ResponseInterface $response The response.
|
||||
* @param callable $next Callback to invoke the next middleware.
|
||||
* @return \Psr\Http\Message\ResponseInterface A response
|
||||
*/
|
||||
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
|
||||
{
|
||||
return $next($request, $response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?php
|
||||
namespace {{ namespace }}\Model\Behavior;
|
||||
|
||||
use Cake\ORM\Behavior;
|
||||
use Cake\ORM\Table;
|
||||
|
||||
/**
|
||||
* {{ name }} behavior
|
||||
*/
|
||||
class {{ name }}Behavior extends Behavior
|
||||
{
|
||||
/**
|
||||
* Default configuration.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_defaultConfig = [];
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
{% set propertyHintMap = DocBlock.buildEntityPropertyHintTypeMap(propertySchema ?: []) %}
|
||||
{% set associationHintMap = DocBlock.buildEntityAssociationHintTypeMap(propertySchema ?: []) %}
|
||||
{% set annotations = DocBlock.propertyHints(propertyHintMap) %}
|
||||
|
||||
{%- if associationHintMap %}
|
||||
{%- set annotations = annotations|merge(['']) %}
|
||||
{%- set annotations = annotations|merge(DocBlock.propertyHints(associationHintMap)) %}
|
||||
{% endif %}
|
||||
|
||||
{%- set accessible = Bake.getFieldAccessibility(fields, primaryKey) %}
|
||||
<?php
|
||||
namespace {{ namespace }}\Model\Entity;
|
||||
|
||||
use Cake\ORM\Entity;
|
||||
|
||||
{{ DocBlock.classDescription(name, 'Entity', annotations)|raw }}
|
||||
class {{ name }} extends Entity
|
||||
{
|
||||
{% if accessible %}
|
||||
/**
|
||||
* Fields that can be mass assigned using newEntity() or patchEntity().
|
||||
*
|
||||
* Note that when '*' is set to true, this allows all unspecified fields to
|
||||
* be mass assigned. For security purposes, it is advised to set '*' to false
|
||||
* (or remove it), and explicitly make individual fields accessible as needed.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_accessible = [{{ Bake.stringifyList(accessible, {'quotes': false})|raw }}];
|
||||
{% endif %}
|
||||
{% if accessible and hidden %}
|
||||
|
||||
{% endif %}
|
||||
{%- if hidden %}
|
||||
/**
|
||||
* Fields that are excluded from JSON versions of the entity.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_hidden = [{{ Bake.stringifyList(hidden)|raw }}];
|
||||
{% endif %}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
{% set annotations = DocBlock.buildTableAnnotations(associations, associationInfo, behaviors, entity, namespace) %}
|
||||
<?php
|
||||
namespace {{ namespace }}\Model\Table;
|
||||
|
||||
{% set uses = ['use Cake\\ORM\\Query;', 'use Cake\\ORM\\RulesChecker;', 'use Cake\\ORM\\Table;', 'use Cake\\Validation\\Validator;'] %}
|
||||
{{ uses|join('\n')|raw }}
|
||||
|
||||
{{ DocBlock.classDescription(name, 'Model', annotations)|raw }}
|
||||
class {{ name }}Table extends Table
|
||||
{
|
||||
/**
|
||||
* Initialize method
|
||||
*
|
||||
* @param array $config The configuration for the Table.
|
||||
* @return void
|
||||
*/
|
||||
public function initialize(array $config)
|
||||
{
|
||||
parent::initialize($config);
|
||||
|
||||
{% if table %}
|
||||
$this->setTable('{{ table }}');
|
||||
{% endif %}
|
||||
|
||||
{%- if displayField %}
|
||||
$this->setDisplayField('{{ displayField }}');
|
||||
{% endif %}
|
||||
|
||||
{%- if primaryKey %}
|
||||
{%- if primaryKey is iterable and primaryKey|length > 1 %}
|
||||
$this->setPrimaryKey([{{ Bake.stringifyList(primaryKey, {'indent': false})|raw }}]);
|
||||
{{- "\n" }}
|
||||
{%- else %}
|
||||
$this->setPrimaryKey('{{ primaryKey|as_array|first }}');
|
||||
{{- "\n" }}
|
||||
{%- endif %}
|
||||
{% endif %}
|
||||
|
||||
{%- if behaviors %}
|
||||
|
||||
{% endif %}
|
||||
|
||||
{%- for behavior, behaviorData in behaviors %}
|
||||
$this->addBehavior('{{ behavior }}'{{ (behaviorData ? (", [" ~ Bake.stringifyList(behaviorData, {'indent': 3, 'quotes': false})|raw ~ ']') : '')|raw }});
|
||||
{% endfor %}
|
||||
|
||||
{%- if associations.belongsTo or associations.hasMany or associations.belongsToMany %}
|
||||
|
||||
{% endif %}
|
||||
|
||||
{%- for type, assocs in associations %}
|
||||
{%- for assoc in assocs %}
|
||||
{%- set assocData = [] %}
|
||||
{%- for key, val in assoc if key is not same as('alias') %}
|
||||
{%- set assocData = assocData|merge({(key): val}) %}
|
||||
{%- endfor %}
|
||||
$this->{{ type }}('{{ assoc.alias }}', [{{ Bake.stringifyList(assocData, {'indent': 3})|raw }}]);
|
||||
{{- "\n" }}
|
||||
{%- endfor %}
|
||||
{% endfor %}
|
||||
}
|
||||
{{- "\n" }}
|
||||
|
||||
{%- if validation %}
|
||||
|
||||
/**
|
||||
* Default validation rules.
|
||||
*
|
||||
* @param \Cake\Validation\Validator $validator Validator instance.
|
||||
* @return \Cake\Validation\Validator
|
||||
*/
|
||||
public function validationDefault(Validator $validator)
|
||||
{
|
||||
{% for field, rules in validation %}
|
||||
{% set validationMethods = Bake.getValidationMethods(field, rules) %}
|
||||
{% if validationMethods %}
|
||||
$validator
|
||||
{% for validationMethod in validationMethods %}
|
||||
{% if loop.last %}
|
||||
{% set validationMethod = validationMethod ~ ';' %}
|
||||
{% endif %}
|
||||
{{ validationMethod|raw }}
|
||||
{% endfor %}
|
||||
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
return $validator;
|
||||
}
|
||||
{% endif %}
|
||||
|
||||
{%- if rulesChecker %}
|
||||
|
||||
/**
|
||||
* Returns a rules checker object that will be used for validating
|
||||
* application integrity.
|
||||
*
|
||||
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
|
||||
* @return \Cake\ORM\RulesChecker
|
||||
*/
|
||||
public function buildRules(RulesChecker $rules)
|
||||
{
|
||||
{% for field, rule in rulesChecker %}
|
||||
$rules->add($rules->{{ rule.name }}(['{{ field }}']{{ (rule.extra is defined and rule.extra ? (", '#{rule.extra}'") : '')|raw }}));
|
||||
{% endfor %}
|
||||
|
||||
return $rules;
|
||||
}
|
||||
{% endif %}
|
||||
|
||||
{%- if connection is not same as('default') %}
|
||||
|
||||
/**
|
||||
* Returns the database connection name to use by default.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function defaultConnectionName()
|
||||
{
|
||||
return '{{ connection }}';
|
||||
}
|
||||
{% endif %}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/composer.lock
|
||||
/phpunit.xml
|
||||
/vendor
|
||||
config/Migrations/schema-dump-default.lock
|
||||
@@ -0,0 +1,26 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
# {{ plugin }} plugin for CakePHP
|
||||
|
||||
## Installation
|
||||
|
||||
You can install this plugin into your CakePHP application using [composer](https://getcomposer.org).
|
||||
|
||||
The recommended way to install composer packages is:
|
||||
|
||||
```
|
||||
composer require {{ package }}
|
||||
```
|
||||
@@ -0,0 +1,39 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
{% set namespace = namespace|replace({'\\': '\\\\'}) %}
|
||||
{
|
||||
"name": "{{ package }}",
|
||||
"description": "{{ plugin }} plugin for CakePHP",
|
||||
"type": "cakephp-plugin",
|
||||
"license": "MIT",
|
||||
"require": {
|
||||
"cakephp/cakephp": "^3.5"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^5.7.14|^6.0"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"{{ namespace }}\\": "src/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"{{ namespace }}\\Test\\": "tests/",
|
||||
"Cake\\Test\\": "vendor/cakephp/cakephp/tests/"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?php
|
||||
use Cake\Routing\RouteBuilder;
|
||||
use Cake\Routing\Router;
|
||||
use Cake\Routing\Route\DashedRoute;
|
||||
|
||||
Router::plugin(
|
||||
'{{ plugin }}',
|
||||
['path' => '/{{ routePath }}'],
|
||||
function (RouteBuilder $routes) {
|
||||
$routes->fallbacks(DashedRoute::class);
|
||||
}
|
||||
);
|
||||
@@ -0,0 +1,50 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<phpunit
|
||||
colors="true"
|
||||
processIsolation="false"
|
||||
stopOnFailure="false"
|
||||
bootstrap="tests/bootstrap.php"
|
||||
>
|
||||
<php>
|
||||
<ini name="memory_limit" value="-1"/>
|
||||
<ini name="apc.enable_cli" value="1"/>
|
||||
</php>
|
||||
|
||||
<!-- Add any additional test suites you want to run here -->
|
||||
<testsuites>
|
||||
<testsuite name="{{ plugin }}">
|
||||
<directory>tests/TestCase/</directory>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
|
||||
<!-- Setup a listener for fixtures -->
|
||||
<listeners>
|
||||
<listener class="Cake\TestSuite\Fixture\FixtureInjector">
|
||||
<arguments>
|
||||
<object class="Cake\TestSuite\Fixture\FixtureManager"/>
|
||||
</arguments>
|
||||
</listener>
|
||||
</listeners>
|
||||
|
||||
<filter>
|
||||
<whitelist>
|
||||
<directory suffix=".php">src/</directory>
|
||||
</whitelist>
|
||||
</filter>
|
||||
|
||||
</phpunit>
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?php
|
||||
|
||||
namespace {{ namespace }}\Controller;
|
||||
|
||||
use {{ baseNamespace }}\Controller\AppController as BaseController;
|
||||
|
||||
class AppController extends BaseController
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 1.7.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?php
|
||||
|
||||
namespace {{ namespace }};
|
||||
|
||||
use Cake\Core\BasePlugin;
|
||||
|
||||
/**
|
||||
* Plugin for {{ namespace }}
|
||||
*/
|
||||
class Plugin extends BasePlugin
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
{#
|
||||
/**
|
||||
* Tests bootstrap file
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?php
|
||||
/**
|
||||
* Test suite bootstrap for {{ plugin }}.
|
||||
*
|
||||
* This function is used to find the location of CakePHP whether CakePHP
|
||||
* has been installed as a dependency of the plugin, or the plugin is itself
|
||||
* installed as a dependency of an application.
|
||||
*/
|
||||
$findRoot = function ($root) {
|
||||
do {
|
||||
$lastRoot = $root;
|
||||
$root = dirname($root);
|
||||
if (is_dir($root . '/vendor/cakephp/cakephp')) {
|
||||
return $root;
|
||||
}
|
||||
} while ($root !== $lastRoot);
|
||||
|
||||
throw new Exception("Cannot find the root of the application, unable to run tests");
|
||||
};
|
||||
$root = $findRoot(__FILE__);
|
||||
unset($findRoot);
|
||||
|
||||
chdir($root);
|
||||
|
||||
require_once $root . '/vendor/autoload.php';
|
||||
|
||||
/**
|
||||
* Define fallback values for required constants and configuration.
|
||||
* To customize constants and configuration remove this require
|
||||
* and define the data required by your plugin here.
|
||||
*/
|
||||
require_once $root . '/vendor/cakephp/cakephp/tests/bootstrap.php';
|
||||
|
||||
if (file_exists($root . '/config/bootstrap.php')) {
|
||||
require $root . '/config/bootstrap.php';
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
@@ -0,0 +1,36 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?php
|
||||
namespace {{ namespace }}\Shell\Helper;
|
||||
|
||||
use Cake\Console\Helper;
|
||||
|
||||
/**
|
||||
* {{ name }} shell helper.
|
||||
*/
|
||||
class {{ name }}Helper extends Helper
|
||||
{
|
||||
/**
|
||||
* Output method.
|
||||
*
|
||||
* Generate the output for this shell helper.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function output($args)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?php
|
||||
namespace {{ namespace }}\Shell;
|
||||
|
||||
use Cake\Console\Shell;
|
||||
|
||||
/**
|
||||
* {{ name }} shell command.
|
||||
*/
|
||||
class {{ name }}Shell extends Shell
|
||||
{
|
||||
/**
|
||||
* Manage the available sub-commands along with their arguments and help
|
||||
*
|
||||
* @see http://book.cakephp.org/3.0/en/console-and-shells.html#configuring-options-and-generating-help
|
||||
*
|
||||
* @return \Cake\Console\ConsoleOptionParser
|
||||
*/
|
||||
public function getOptionParser()
|
||||
{
|
||||
$parser = parent::getOptionParser();
|
||||
|
||||
return $parser;
|
||||
}
|
||||
|
||||
/**
|
||||
* main() method.
|
||||
*
|
||||
* @return bool|int|null Success or error code.
|
||||
*/
|
||||
public function main()
|
||||
{
|
||||
$this->out($this->OptionParser->help());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?php
|
||||
namespace {{ namespace }}\Shell\Task;
|
||||
|
||||
use Cake\Console\Shell;
|
||||
|
||||
/**
|
||||
* {{ name }} shell task.
|
||||
*/
|
||||
class {{ name }}Task extends Shell
|
||||
{
|
||||
/**
|
||||
* Manage the available sub-commands along with their arguments and help
|
||||
*
|
||||
* @see http://book.cakephp.org/3.0/en/console-and-shells.html#configuring-options-and-generating-help
|
||||
* @return \Cake\Console\ConsoleOptionParser
|
||||
*/
|
||||
public function getOptionParser()
|
||||
{
|
||||
$parser = parent::getOptionParser();
|
||||
|
||||
return $parser;
|
||||
}
|
||||
|
||||
/**
|
||||
* main() method.
|
||||
*
|
||||
* @return bool|int|null Success or error code.
|
||||
*/
|
||||
public function main()
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?php
|
||||
/**
|
||||
* @var \{{ namespace }}\View\AppView $this
|
||||
* @var \{{ entityClass }} ${{ singularVar }}
|
||||
*/
|
||||
?>
|
||||
{% element 'form' %}
|
||||
@@ -0,0 +1,22 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?php
|
||||
/**
|
||||
* @var \{{ namespace }}\View\AppView $this
|
||||
* @var \{{ entityClass }} ${{ singularVar }}
|
||||
*/
|
||||
?>
|
||||
{% element 'form' %}
|
||||
@@ -0,0 +1,90 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?php
|
||||
/**
|
||||
* @var \{{ namespace }}\View\AppView $this
|
||||
* @var \{{ entityClass }}[]|\Cake\Collection\CollectionInterface ${{ pluralVar }}
|
||||
*/
|
||||
?>
|
||||
{% set fields = Bake.filterFields(fields, schema, modelObject, indexColumns, ['binary', 'text']) %}
|
||||
<nav class="large-3 medium-4 columns" id="actions-sidebar">
|
||||
<ul class="side-nav">
|
||||
<li class="heading"><?= __('Actions') ?></li>
|
||||
<li><?= $this->Html->link(__('New {{ singularHumanName }}'), ['action' => 'add']) ?></li>
|
||||
{% set done = [] %}
|
||||
{% for type, data in associations %}
|
||||
{% for alias, details in data %}
|
||||
{% if details.navLink and details.controller is not same as(_view.name) and details.controller not in done %}
|
||||
<li><?= $this->Html->link(__('List {{ alias|underscore|humanize }}'), ['controller' => '{{ details.controller }}', 'action' => 'index']) ?></li>
|
||||
<li><?= $this->Html->link(__('New {{ alias|singularize|underscore|humanize }}'), ['controller' => '{{ details.controller }}', 'action' => 'add']) ?></li>
|
||||
{% set done = done|merge([details.controller]) %}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</nav>
|
||||
<div class="{{ pluralVar }} index large-9 medium-8 columns content">
|
||||
<h3><?= __('{{ pluralHumanName }}') ?></h3>
|
||||
<table cellpadding="0" cellspacing="0">
|
||||
<thead>
|
||||
<tr>
|
||||
{% for field in fields %}
|
||||
<th scope="col"><?= $this->Paginator->sort('{{ field }}') ?></th>
|
||||
{% endfor %}
|
||||
<th scope="col" class="actions"><?= __('Actions') ?></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach (${{ pluralVar }} as ${{ singularVar }}): ?>
|
||||
<tr>
|
||||
{% for field in fields %}
|
||||
{% set isKey = false %}
|
||||
{% if associations.BelongsTo %}
|
||||
{% for alias, details in associations.BelongsTo if field == details.foreignKey %}
|
||||
{% set isKey = true %}
|
||||
<td><?= ${{ singularVar }}->has('{{ details.property }}') ? $this->Html->link(${{ singularVar }}->{{ details.property }}->{{ details.displayField }}, ['controller' => '{{ details.controller }}', 'action' => 'view', ${{ singularVar }}->{{ details.property }}->{{ details.primaryKey[0] }}]) : '' ?></td>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% if isKey is not same as(true) %}
|
||||
{% set columnData = Bake.columnData(field, schema) %}
|
||||
{% if columnData.type not in ['integer', 'float', 'decimal', 'biginteger', 'smallinteger', 'tinyinteger'] %}
|
||||
<td><?= h(${{ singularVar }}->{{ field }}) ?></td>
|
||||
{% else %}
|
||||
<td><?= $this->Number->format(${{ singularVar }}->{{ field }}) ?></td>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% set pk = '$' ~ singularVar ~ '->' ~ primaryKey[0] %}
|
||||
<td class="actions">
|
||||
<?= $this->Html->link(__('View'), ['action' => 'view', {{ pk|raw }}]) ?>
|
||||
<?= $this->Html->link(__('Edit'), ['action' => 'edit', {{ pk|raw }}]) ?>
|
||||
<?= $this->Form->postLink(__('Delete'), ['action' => 'delete', {{ pk|raw }}], ['confirm' => __('Are you sure you want to delete # {0}?', {{ pk|raw }})]) ?>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="paginator">
|
||||
<ul class="pagination">
|
||||
<?= $this->Paginator->first('<< ' . __('first')) ?>
|
||||
<?= $this->Paginator->prev('< ' . __('previous')) ?>
|
||||
<?= $this->Paginator->numbers() ?>
|
||||
<?= $this->Paginator->next(__('next') . ' >') ?>
|
||||
<?= $this->Paginator->last(__('last') . ' >>') ?>
|
||||
</ul>
|
||||
<p><?= $this->Paginator->counter(['format' => __('Page {{ '{{' }}page{{ '}}' }} of {{ '{{' }}pages{{ '}}' }}, showing {{ '{{' }}current{{ '}}' }} record(s) out of {{ '{{' }}count{{ '}}' }} total')]) ?></p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,31 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?php
|
||||
/**
|
||||
* @var \{{ namespace }}\View\AppView $this
|
||||
*/
|
||||
?>
|
||||
<div class="{{ pluralVar }} form">
|
||||
<?= $this->Flash->render('auth') ?>
|
||||
<?= $this->Form->create() ?>
|
||||
<fieldset>
|
||||
<legend><?= __('Please enter your username and password') ?></legend>
|
||||
<?= $this->Form->control('username') ?>
|
||||
<?= $this->Form->control('password') ?>
|
||||
</fieldset>
|
||||
<?= $this->Form->button(__('Login')); ?>
|
||||
<?= $this->Form->end() ?>
|
||||
</div>
|
||||
@@ -0,0 +1,137 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?php
|
||||
/**
|
||||
* @var \{{ namespace }}\View\AppView $this
|
||||
* @var \{{ entityClass }} ${{ singularVar }}
|
||||
*/
|
||||
?>
|
||||
{% set associations = {'BelongsTo': [], 'HasOne': [], 'HasMany': [], 'BelongsToMany': []}|merge(associations) %}
|
||||
{% set fieldsData = Bake.getViewFieldsData(fields, schema, associations) %}
|
||||
{% set associationFields = fieldsData.associationFields %}
|
||||
{% set groupedFields = fieldsData.groupedFields %}
|
||||
{% set pK = '$' ~ singularVar ~ '->' ~ primaryKey[0] %}
|
||||
<nav class="large-3 medium-4 columns" id="actions-sidebar">
|
||||
<ul class="side-nav">
|
||||
<li class="heading"><?= __('Actions') ?></li>
|
||||
<li><?= $this->Html->link(__('Edit {{ singularHumanName }}'), ['action' => 'edit', {{ pK|raw }}]) ?> </li>
|
||||
<li><?= $this->Form->postLink(__('Delete {{ singularHumanName }}'), ['action' => 'delete', {{ pK|raw }}], ['confirm' => __('Are you sure you want to delete # {0}?', {{ pK|raw }})]) ?> </li>
|
||||
<li><?= $this->Html->link(__('List {{ pluralHumanName }}'), ['action' => 'index']) ?> </li>
|
||||
<li><?= $this->Html->link(__('New {{ singularHumanName }}'), ['action' => 'add']) ?> </li>
|
||||
{% set done = [] %}
|
||||
{% for type, data in associations %}
|
||||
{% for alias, details in data %}
|
||||
{% if details.controller is not same as(_view.name) and details.controller not in done %}
|
||||
<li><?= $this->Html->link(__('List {{ alias|underscore|humanize }}'), ['controller' => '{{ details.controller }}', 'action' => 'index']) ?> </li>
|
||||
<li><?= $this->Html->link(__('New {{ alias|underscore|singularize|humanize }}'), ['controller' => '{{ details.controller }}', 'action' => 'add']) ?> </li>
|
||||
{% set done = done|merge(['controller']) %}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</nav>
|
||||
<div class="{{ pluralVar }} view large-9 medium-8 columns content">
|
||||
<h3><?= h(${{ singularVar }}->{{ displayField }}) ?></h3>
|
||||
<table class="vertical-table">
|
||||
{% if groupedFields['string'] %}
|
||||
{% for field in groupedFields['string'] %}
|
||||
{% if associationFields[field] %}
|
||||
{% set details = associationFields[field] %}
|
||||
<tr>
|
||||
<th scope="row"><?= __('{{ details.property|humanize }}') ?></th>
|
||||
<td><?= ${{ singularVar }}->has('{{ details.property }}') ? $this->Html->link(${{ singularVar }}->{{ details.property }}->{{ details.displayField }}, ['controller' => '{{ details.controller }}', 'action' => 'view', ${{ singularVar }}->{{ details.property }}->{{ details.primaryKey[0] }}]) : '' ?></td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr>
|
||||
<th scope="row"><?= __('{{ field|humanize }}') ?></th>
|
||||
<td><?= h(${{ singularVar }}->{{ field }}) ?></td>
|
||||
</tr>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% if associations.HasOne %}
|
||||
{% for alias, details in associations.HasOne %}
|
||||
<tr>
|
||||
<th scope="row"><?= __('{{ alias|underscore|singularize|humanize }}') ?></th>
|
||||
<td><?= ${{ singularVar }}->has('{{ details.property }}') ? $this->Html->link(${{ singularVar }}->{{ details.property }}->{{ details.displayField }}, ['controller' => '{{ details.controller }}', 'action' => 'view', ${{ singularVar }}->{{ details.property }}->{{ details.primaryKey[0] }}]) : '' ?></td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% if groupedFields.number %}
|
||||
{% for field in groupedFields.number %}
|
||||
<tr>
|
||||
<th scope="row"><?= __('{{ field|humanize }}') ?></th>
|
||||
<td><?= $this->Number->format(${{ singularVar }}->{{ field }}) ?></td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% if groupedFields.date %}
|
||||
{% for field in groupedFields.date %}
|
||||
<tr>
|
||||
<th scope="row"><?= __('{{ field|humanize }}') ?></th>
|
||||
<td><?= h(${{ singularVar }}->{{ field }}) ?></td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% if groupedFields.boolean %}
|
||||
{% for field in groupedFields.boolean %}
|
||||
<tr>
|
||||
<th scope="row"><?= __('{{ field|humanize }}') ?></th>
|
||||
<td><?= ${{ singularVar }}->{{ field }} ? __('Yes') : __('No'); ?></td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
</table>
|
||||
{% if groupedFields.text %}
|
||||
{% for field in groupedFields.text %}
|
||||
<div class="row">
|
||||
<h4><?= __('{{ field|humanize }}') ?></h4>
|
||||
<?= $this->Text->autoParagraph(h(${{ singularVar }}->{{ field }})); ?>
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% set relations = associations.BelongsToMany|merge(associations.HasMany) %}
|
||||
{% for alias, details in relations %}
|
||||
{% set otherSingularVar = alias|variable %}
|
||||
{% set otherPluralHumanName = details.controller|underscore|humanize %}
|
||||
<div class="related">
|
||||
<h4><?= __('Related {{ otherPluralHumanName }}') ?></h4>
|
||||
<?php if (!empty(${{ singularVar }}->{{ details.property }})): ?>
|
||||
<table cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
{% for field in details.fields %}
|
||||
<th scope="col"><?= __('{{ field|humanize }}') ?></th>
|
||||
{% endfor %}
|
||||
<th scope="col" class="actions"><?= __('Actions') ?></th>
|
||||
</tr>
|
||||
<?php foreach (${{ singularVar }}->{{ details.property }} as ${{ otherSingularVar }}): ?>
|
||||
<tr>
|
||||
{% for field in details.fields %}
|
||||
<td><?= h(${{ otherSingularVar }}->{{ field }}) ?></td>
|
||||
{% endfor %}
|
||||
{% set otherPk = '$' ~ otherSingularVar ~ '->' ~ details.primaryKey[0] %}
|
||||
<td class="actions">
|
||||
<?= $this->Html->link(__('View'), ['controller' => '{{ details.controller }}', 'action' => 'view', {{ otherPk|raw }}]) ?>
|
||||
<?= $this->Html->link(__('Edit'), ['controller' => '{{ details.controller }}', 'action' => 'edit', {{ otherPk|raw }}]) ?>
|
||||
<?= $this->Form->postLink(__('Delete'), ['controller' => '{{ details.controller }}', 'action' => 'delete', {{ otherPk|raw }}], ['confirm' => __('Are you sure you want to delete # {0}?', {{ otherPk|raw }})]) ?>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</table>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
@@ -0,0 +1,51 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?php
|
||||
namespace {{ namespace }}\View\Cell{{ prefix }};
|
||||
|
||||
use Cake\View\Cell;
|
||||
|
||||
/**
|
||||
* {{ name }} cell
|
||||
*/
|
||||
class {{ name }}Cell extends Cell
|
||||
{
|
||||
/**
|
||||
* List of valid options that can be passed into this
|
||||
* cell's constructor.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_validCellOptions = [];
|
||||
|
||||
/**
|
||||
* Initialization logic run at the end of object construction.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function initialize()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Default display method.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function display()
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
{#
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?php
|
||||
namespace {{ namespace }}\View\Helper;
|
||||
|
||||
use Cake\View\Helper;
|
||||
use Cake\View\View;
|
||||
|
||||
/**
|
||||
* {{ name }} helper
|
||||
*/
|
||||
class {{ name }}Helper extends Helper
|
||||
{
|
||||
/**
|
||||
* Default configuration.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_defaultConfig = [];
|
||||
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
{#
|
||||
/**
|
||||
* Fixture Template file
|
||||
*
|
||||
* Fixture Template used when baking fixtures with bake
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
#}
|
||||
<?php
|
||||
namespace {{ namespace }}\Test\Fixture;
|
||||
|
||||
use Cake\TestSuite\Fixture\TestFixture;
|
||||
|
||||
/**
|
||||
* {{ name }}Fixture
|
||||
*/
|
||||
class {{ name }}Fixture extends TestFixture
|
||||
{
|
||||
{% if table %}
|
||||
/**
|
||||
* Table name
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $table = '{{ table|raw }}';
|
||||
{% endif %}
|
||||
|
||||
{%- if import %}
|
||||
/**
|
||||
* Import
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $import = {{ import|raw }};
|
||||
|
||||
{% endif %}
|
||||
|
||||
{%- if schema %}
|
||||
/**
|
||||
* Fields
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
// @codingStandardsIgnoreStart
|
||||
public $fields = {{ schema|raw }};
|
||||
// @codingStandardsIgnoreEnd
|
||||
{% endif %}
|
||||
|
||||
{%- if records %}
|
||||
/**
|
||||
* Init method
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function init()
|
||||
{
|
||||
$this->records = {{ records|raw }};
|
||||
parent::init();
|
||||
}
|
||||
{% endif %}
|
||||
}
|
||||
Loaded 100 of 6566 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user