Skip to content

Commit

Permalink
Merge pull request #3 from CakeDC/feature/refactor
Browse files Browse the repository at this point in the history
refactor some code to inertiatrait and build pagination links method
  • Loading branch information
steinkel authored May 1, 2024
2 parents 6d26e63 + 252b69c commit efeacdb
Show file tree
Hide file tree
Showing 12 changed files with 76 additions and 78 deletions.
4 changes: 2 additions & 2 deletions Docs/Documentation/CakePHP-Docker.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
CakePHP installation and configuration example using Docker

```
$> composer create-project --prefer-dist cakephp/app:~4.5 inertia_app
$> composer create-project --prefer-dist cakephp/app:~5.0 inertia_app
$> cd inertia_app
$> cp config/app_local.example.php config/app_local.php
```
Expand Down Expand Up @@ -49,4 +49,4 @@ launch container
$> docker-compose up -d
```

go to http://localhost:9099/
go to http://localhost:9099/
2 changes: 1 addition & 1 deletion config/sql/example(postgresql).psql
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ CREATE TABLE public.pages (
created timestamp NOT NULL,
modified timestamp NOT NULL,
category_id int4 NULL,
published_date timestamp NULL,
published_date date NULL,
CONSTRAINT pages_pkey PRIMARY KEY (id)
);

Expand Down
2 changes: 1 addition & 1 deletion resources/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { createInertiaApp } from '@inertiajs/vue3'

createInertiaApp({
title: title => title ? `${title} - Vue App` : 'Vue App',
resolve: (name) => require(`./Components/${name}.vue`),
resolve: name => import(`./Components/${name}`),
setup({ el, App, props, plugin }) {
return createApp({ render: () => h(App, props) })
.use(plugin)
Expand Down
8 changes: 8 additions & 0 deletions resources/webpack.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const path = require('path')
const webpack = require('webpack');

module.exports = {
output: { chunkFilename: 'js/[name].js?id=[chunkhash]' },
Expand All @@ -11,4 +12,11 @@ module.exports = {
devServer: {
allowedHosts: 'all',
},
plugins: [
new webpack.DefinePlugin({
__VUE_OPTIONS_API__: 'true',
__VUE_PROD_DEVTOOLS__: 'false',
__VUE_PROD_HYDRATION_MISMATCH_DETAILS__: 'false'
}),
]
}
16 changes: 10 additions & 6 deletions src/Traits/InertiaResponseTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
use Cake\Event\EventInterface;
use Cake\Core\InstanceConfigTrait;
use Cake\Datasource\Paging\PaginatedInterface;
use Cake\I18n\Date;
use Cake\Routing\Router;

trait InertiaResponseTrait
{
Expand All @@ -30,10 +32,12 @@ trait InertiaResponseTrait
'JsonViewClass' => \CakeDC\Inertia\View\InertiaJsonView::class,
];

public function buildPaginationLinks(PaginatedInterface $paging)
public function buildPaginationLinks(PaginatedInterface $paging, string $controller, string $action)
{
$pagingParams = $paging->pagingParams();
$params = [];
$baseUrl = Router::url(['controller' => $controller, 'action' => $action]);

if (isset($pagingParams['sort'])) {
$params[] = 'sort' . '=' . $pagingParams['sort'];
}
Expand All @@ -43,24 +47,24 @@ public function buildPaginationLinks(PaginatedInterface $paging)
$params = implode('&', $params);

if ($pagingParams['currentPage'] > 1) {
$links[] = ['url' => 'index?page=1' . $params, 'label' => '<< ' . __('first')];
$links[] = ['url' => $baseUrl . '?page=1' . $params, 'label' => '<< ' . __('first')];
}
if ($pagingParams['hasPrevPage']) {
$links[] = [
'url' => 'index?page=' . ($pagingParams['currentPage'] - 1) . $params,
'url' => $baseUrl . '?page=' . ($pagingParams['currentPage'] - 1) . $params,
'label' => '< ' . __('previous')];
}
for ($i = 1; $i <= $pagingParams['pageCount']; $i++) {
$links[] = ['url' => 'index?page=' . $i . $params, 'label' => $i];
$links[] = ['url' => $baseUrl . '?page=' . $i . $params, 'label' => $i];
}
if ($pagingParams['hasNextPage']) {
$links[] = [
'url' => 'index?page=' . ($pagingParams['currentPage'] + 1) . $params,
'url' => $baseUrl . '?page=' . ($pagingParams['currentPage'] + 1) . $params,
'label' => __('next') . ' >'];
}
if ($pagingParams['currentPage'] < $pagingParams['pageCount']) {
$links[] = [
'url' => 'index?page=' . $pagingParams['pageCount'] . $params,
'url' => $baseUrl . '?page=' . $pagingParams['pageCount'] . $params,
'label' => __('last') . ' >>'];
}

Expand Down
19 changes: 19 additions & 0 deletions templates/bake/Model/table.twig
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
namespace: fileBuilder.namespace,
classImports: fileBuilder.classImports(['Cake\\ORM\\Query\\SelectQuery', 'Cake\\ORM\\RulesChecker', 'Cake\\ORM\\Table', 'Cake\\Validation\\Validator']),
}) }}
use ArrayObject;
use Cake\Event\EventInterface;

{{ DocBlock.classDescription(name, 'Model', annotations)|raw }}
class {{ name }}Table extends Table{{ fileBuilder.classBuilder.implements ? ' implements ' ~ fileBuilder.classBuilder.implements|join(', ') : '' }}
Expand Down Expand Up @@ -188,4 +190,21 @@ class {{ name }}Table extends Table{{ fileBuilder.classBuilder.implements ? ' im

return $query;
}

/**
* Parse date fields before patch entity
*
* @param \Cake\Event\EventInterface $event
* @param \ArrayObject $data
* @param \ArrayObject $options
* @return void
*/
public function beforeMarshal(EventInterface $event, ArrayObject $data, ArrayObject $options): void
{
foreach ($this->getSchema()->columns() as $column) {
if ($this->getSchema()->getColumnType($column) === 'timestampfractional' && $data[$column] !== null) {
$data[$column] = Date::parseDate($data[$column], 'YYYY-MM-dd');
}
}
}
}
6 changes: 3 additions & 3 deletions templates/bake/Template/index.twig
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@
const props = defineProps({
csrfToken: String,
flash: [],
{{ pluralVar }}: [],
flash: Array|Object,
{{ pluralVar }}: Array|Object,
sort: String,
direction: String,
links: [],
links: Array|Object,
})
const direction = ref(0)
Expand Down
2 changes: 1 addition & 1 deletion templates/bake/Template/view.twig
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
const props = defineProps({
csrfToken: String,
{{singularVar}}: [],
{{singularVar}}: Array|Object,
})
function formatDate(date) {
Expand Down
28 changes: 2 additions & 26 deletions templates/bake/element/Controller/add.twig
Original file line number Diff line number Diff line change
Expand Up @@ -19,32 +19,8 @@
{
$errors = [];
${{ singularName }} = $this->{{ currentModelName }}->newEmptyEntity();
if ($this->request->is('post')) {
$data = $this->request->getData();

foreach ($data as $key => $val) {
if (is_array($val)) {
if (array_key_exists('_ids', $val)) {
$newItems = [];
foreach ($val as $item) {
foreach ($item as $value) {
$newItems[] = $value['id'];
}
}
$data[$key]['_ids'] = $newItems;
}
}
}

$db = \Cake\Datasource\ConnectionManager::get('default');
$collection = $db->getSchemaCollection();
$tableSchema = $collection->describe('{{pluralHumanName}}');
foreach ($tableSchema->columns() as $column) {
if ($tableSchema->getColumnType($column) == 'timestampfractional' && $data[$column] !== null) {
$data[$column] = \Cake\I18n\FrozenDate::parseDate($data[$column], 'YYYY-MM-dd');
}
}
${{ singularName }} = $this->{{ currentModelName }}->patchEntity(${{ singularName }}, $data);
if ($this->getRequest()->is('post')) {
${{ singularName }} = $this->{{ currentModelName }}->patchEntity(${{ singularName }}, $this->getRequest()->getData());
if ($this->{{ currentModelName }}->save(${{ singularName }})) {
$this->Flash->success(__('The {{ singularHumanName|lower }} has been saved.'));

Expand Down
27 changes: 1 addition & 26 deletions templates/bake/element/Controller/edit.twig
Original file line number Diff line number Diff line change
Expand Up @@ -26,32 +26,7 @@
'contain' => {{ Bake.exportArray(belongsToMany)|raw }},
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$data = $this->request->getData();

foreach ($data as $key => $val) {
if (is_array($val)) {
if (array_key_exists('_ids', $val)) {
$newItems = [];
foreach ($val as $item) {
foreach ($item as $value) {
$newItems[] = $value['id'];
}
}
$data[$key]['_ids'] = $newItems;
}
}
}

$db = \Cake\Datasource\ConnectionManager::get('default');
$collection = $db->getSchemaCollection();
$tableSchema = $collection->describe('{{pluralHumanName}}');
foreach ($tableSchema->columns() as $column) {
if ($tableSchema->getColumnType($column) == 'timestampfractional') {
$data[$column] = \Cake\I18n\FrozenDate::parseDate($data[$column], 'YYYY-MM-dd');
}
}

${{ singularName }} = $this->{{ currentModelName }}->patchEntity(${{ singularName }}, $data);
${{ singularName }} = $this->{{ currentModelName }}->patchEntity(${{ singularName }}, $this->getRequest()->getData());
if ($this->{{ currentModelName }}->save(${{ singularName }})) {
$this->Flash->success(__('The {{ singularHumanName|lower }} has been saved.'));

Expand Down
10 changes: 6 additions & 4 deletions templates/bake/element/Controller/index.twig
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,23 @@
public function index()
{
{% set belongsTo = Bake.aliasExtractor(modelObj, 'BelongsTo') %}
{% if belongsTo %}
$settings = [
'limit' => 1,
'finder' => 'withRelated',
];
{% endif %}

$paginator = new NumericPaginator();
$pages = $paginator->paginate(
${{ pluralName }} = $paginator->paginate(
$this->fetchTable('{{ currentModelName }}'),
$this->request->getQueryParams(),
$settings
);

$links = $this->buildPaginationLinks(${{ pluralName }});
$links = $this->buildPaginationLinks(
${{ pluralName }},
$this->getRequest()->getParam('controller'),
$this->getRequest()->getParam('action')
);

$this->set(compact('{{ pluralName }}', 'links'));
}
30 changes: 22 additions & 8 deletions templates/bake/element/form.twig
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,23 @@
import { VueEditor } from "vue3-editor";
import Datepicker from 'vue3-datepicker';
import Multiselect from '@vueform/multiselect'
import moment from 'moment'
const props = defineProps({
csrfToken: String,
flash: [],
{{singularVar}}: [],
errors: [],{{- "\n" }}
flash: Array|Object,
{{singularVar}}: Array|Object,
errors: Array|Object,{{- "\n" }}
{%- for field in fields %}
{%- if field not in primaryKey %}
{%- if keyFields[field] is defined %}
{{ keyFields[field] }}: [],
{{ keyFields[field] }}: Array|Object,
{%- endif %}
{%- endif %}
{%- endfor %}
{%- if associations.BelongsToMany is defined %}
{%- for assocName, assocData in associations.BelongsToMany %}
{{- "\n" }} options_{{ assocData.property }}: [],
{{- "\n" }} options_{{ assocData.property }}: Array|Object,
{%- endfor %}
{%- endif %}
{{- "\n" }} })
Expand Down Expand Up @@ -77,6 +78,15 @@
})
function submit() {
{{- "\n" }}
{%- if associations.BelongsToMany is defined %}
{%- for assocName, assocData in associations.BelongsToMany %}
let {{ assocData.property }}Values = [];
for (let key in form.{{ assocData.property }}){
{{ assocData.property }}Values.push(form.{{ assocData.property }}[key].id);
}
{%- endfor %}
{%- endif %}
{{- "\n" }}
{%- if prefix == '' %}
let postUrl = '/{{ pluralVar }}/{{ action }}';
Expand All @@ -91,14 +101,18 @@
{{- "\n" }}
{%- for field in fields %}
{%- if field not in primaryKey %}
{{field}} : form.{{field}},{{- "\n" }}
{%- set fieldData = Bake.columnData(field, schema) %}
{%- if fieldData.type in ['date', 'timestampfractional'] and fieldData.null %}
{{field}} : form.{{field}} !== null ? moment(form.{{field}}.toString()).format("YYYY-MM-DD") : '',{{- "\n" }}
{%- else %}
{{field}} : form.{{field}},{{- "\n" }}
{%- endif %}
{%- endif %}
{%- endfor %}
{%- if associations.BelongsToMany is defined %}
{%- for assocName, assocData in associations.BelongsToMany %}
{{ assocData.property }}: {
_ids : form.{{ assocData.property }}
_ids : {{ assocData.property }}Values
}{{- "\n" }}
{%- endfor %}
{%- endif %}
Expand Down

0 comments on commit efeacdb

Please sign in to comment.