Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/Config/Generators.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,7 @@ class Generators extends BaseConfig
*/
public array $views = [
'make:cell' => 'CodeIgniter\Commands\Generators\Views\cell.tpl.php',
'make:cell_view' => 'CodeIgniter\Commands\Generators\Views\cell_view.tpl.php',
'make:command' => 'CodeIgniter\Commands\Generators\Views\command.tpl.php',
'make:config' => 'CodeIgniter\Commands\Generators\Views\config.tpl.php',
'make:controller' => 'CodeIgniter\Commands\Generators\Views\controller.tpl.php',
Expand Down
6 changes: 3 additions & 3 deletions system/CLI/GeneratorTrait.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -235,15 +235,15 @@ protected function qualifyClassName(): string
$component = singular($this->component);

/**
* @see https://regex101.com/r/a5KNCR/1
* @see https://regex101.com/r/a5KNCR/2
*/
$pattern = sprintf('/([a-z][a-z0-9_\/\\\\]+)(%s)/i', $component);
$pattern = sprintf('/([a-z][a-z0-9_\/\\\\]+)(%s)$/i', $component);

if (preg_match($pattern, $class, $matches) === 1) {
$class = $matches[1] . ucfirst($matches[2]);
}

if ($this->enabledSuffixing && $this->getOption('suffix') && ! strripos($class, $component)) {
if ($this->enabledSuffixing && $this->getOption('suffix') && preg_match($pattern, $class) !== 1) {
$class .= ucfirst($component);
}

Expand Down
28 changes: 13 additions & 15 deletions system/Commands/Generators/CellGenerator.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,7 +65,6 @@ class CellGenerator extends BaseCommand
*/
protected $options = [
'--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".',
'--suffix' => 'Append the component title to the class name (e.g. User => UserCell).',
'--force' => 'Force overwrite existing file.',
];

Expand All@@ -74,27 +73,26 @@ class CellGenerator extends BaseCommand
*/
public function run(array $params)
{
// Generate the Class first
$this->component = 'Cell';
$this->directory = 'Cells';
$this->component = 'Cell';
$this->directory = 'Cells';

$params = array_merge($params, ['suffix' => null]);

$this->template = 'cell.tpl.php';
$this->classNameLang = 'CLI.generator.className.cell';

$this->generateClass($params);

// Generate the View
$this->name = 'make:cell_view';
$this->template = 'cell_view.tpl.php';
$this->classNameLang = 'CLI.generator.viewName.cell';

// Form the view name
$segments = explode('\\', $this->qualifyClassName());

$view = array_pop($segments);
$view = decamelize($view);
$segments[] = $view;
$view = implode('\\', $segments);
$className = $this->qualifyClassName();
$viewName = decamelize(class_basename($className));
$viewName = preg_replace('/([a-z][a-z0-9_\/\\\\]+)(_cell)$/i', '$1', $viewName) ?? $viewName;
$namespace = substr($className, 0, strrpos($className, '\\') + 1);

$this->template = 'cell_view.tpl.php';
$this->generateView($namespace . $viewName, $params);

$this->generateView($view, $params);
return 0;
}
}
49 changes: 32 additions & 17 deletions system/View/Cells/Cell.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@
namespace CodeIgniter\View\Cells;

use CodeIgniter\Traits\PropertiesTrait;
use LogicException;
use ReflectionClass;

/**
Expand DownExpand Up@@ -64,37 +65,51 @@ public function setView(string $view)
* from within the view, this method extracts $data into the
* current scope and captures the output buffer instead of
* relying on the view service.
*
* @throws LogicException
*/
final protected function view(?string $view, array $data = []): string
{
$properties = $this->getPublicProperties();
$properties = $this->includeComputedProperties($properties);
$properties = array_merge($properties, $data);

// If no view is specified, we'll try to guess it based on the class name.
if (empty($view)) {
// According to the docs, the name of the view file should be the
// snake_cased version of the cell's class name, but for backward
// compatibility, the name also accepts '_cell' being omitted.
$ref = new ReflectionClass($this);
$view = decamelize($ref->getShortName());
$viewPath = dirname($ref->getFileName()) . DIRECTORY_SEPARATOR . $view . '.php';
$view = is_file($viewPath) ? $viewPath : str_replace('_cell', '', $view);
$view = (string) $view;

if ($view === '') {
$viewName = decamelize(class_basename(static::class));
$directory = dirname((new ReflectionClass($this))->getFileName()) . DIRECTORY_SEPARATOR;

$possibleView1 = $directory . substr($viewName, 0, strrpos($viewName, '_cell')) . '.php';
$possibleView2 = $directory . $viewName . '.php';
}

// Locate our view, preferring the directory of the class.
if (! is_file($view)) {
// Get the local pathname of the Cell
$ref = new ReflectionClass($this);
$view = dirname($ref->getFileName()) . DIRECTORY_SEPARATOR . $view . '.php';
if ($view !== '' && ! is_file($view)) {
$directory = dirname((new ReflectionClass($this))->getFileName()) . DIRECTORY_SEPARATOR;

$view = $directory . $view . '.php';
}

return (function () use ($properties, $view): string {
$candidateViews = array_filter(
[$view, $possibleView1 ?? '', $possibleView2 ?? ''],
static fn (string $path): bool => $path !== '' && is_file($path)
);

if ($candidateViews === []) {
throw new LogicException(sprintf(
'Cannot locate the view file for the "%s" cell.',
static::class
));
}

$foundView = current($candidateViews);

return (function () use ($properties, $foundView): string {
extract($properties);
ob_start();
include $view;
include $foundView;

return ob_get_clean() ?: '';
return ob_get_clean();
})();
}

Expand Down
18 changes: 18 additions & 0 deletions tests/_support/View/Cells/BadCell.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
<?php

/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace Tests\Support\View\Cells;

use CodeIgniter\View\Cells\Cell;

final class BadCell extends Cell
{
}
39 changes: 29 additions & 10 deletions tests/system/Commands/CellGeneratorTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -46,35 +46,54 @@ protected function getFileContents(string $filepath): string
return file_get_contents($filepath) ?: '';
}

public function testGenerateCell()
public function testGenerateCell(): void
{
command('make:cell RecentCell');

// Check the class was generated
$file = APPPATH . 'Cells/RecentCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$contents = $this->getFileContents($file);
$this->assertStringContainsString('class RecentCell extends Cell', $contents);
$this->assertStringContainsString('class RecentCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/recent_cell.php';
$this->assertStringContainsString('File created: ', $this->getStreamFilterBuffer());
$file = APPPATH . 'Cells/recent.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}

public function testGenerateCellSimpleName()
public function testGenerateCellSimpleName(): void
{
command('make:cell Another');

// Check the class was generated
$file = APPPATH . 'Cells/Another.php';
$file = APPPATH . 'Cells/AnotherCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$contents = $this->getFileContents($file);
$this->assertStringContainsString('class Another extends Cell', $contents);
$this->assertStringContainsString('class AnotherCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/another.php';
$this->assertStringContainsString('File created: ', $this->getStreamFilterBuffer());
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}

public function testGenerateCellWithCellInBetween(): void
{
command('make:cell PippoCellular');

// Check the class was generated
$file = APPPATH . 'Cells/PippoCellularCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertStringContainsString('class PippoCellularCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/pippo_cellular.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}
}
10 changes: 10 additions & 0 deletions tests/system/View/ControlledCellTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,8 +13,10 @@

use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\View\Exceptions\ViewException;
use LogicException;
use Tests\Support\View\Cells\AdditionCell;
use Tests\Support\View\Cells\AwesomeCell;
use Tests\Support\View\Cells\BadCell;
use Tests\Support\View\Cells\ColorsCell;
use Tests\Support\View\Cells\GreetingCell;
use Tests\Support\View\Cells\ListerCell;
Expand DownExpand Up@@ -65,6 +67,14 @@ public function testCellThroughRenderMethodWithExtraData()
$this->assertStringContainsString('42, 23, 16, 15, 8, 4', $result);
}

public function testCellThrowsExceptionWhenCannotFindTheViewFile()
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage('Cannot locate the view file for the "Tests\\Support\\View\\Cells\\BadCell" cell.');

view_cell(BadCell::class);
}

public function testCellWithParameters()
{
$result = view_cell(GreetingCell::class, 'greeting=Hi, name=CodeIgniter');
Expand Down
8 changes: 8 additions & 0 deletions user_guide_src/source/changelogs/v4.3.5.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,13 +18,21 @@ Message Changes
Changes
*******

- **make:cell** When creating a new cell, the controller would always have the ``Cell`` suffixed to the class name.
For the view file, the final ``_cell`` is always removed.
- **Cells** For compatibility with previous versions, view filenames ending with ``_cell`` can still be
located by the ``Cell`` as long as auto-detection of view file is enabled (via setting the ``$view`` property
to an empty string).

Deprecations
************

Bugs Fixed
**********

- **Validation:** Fixed a bug where a closure used in combination with ``permit_empty`` or ``if_exist`` rules was causing an error.
- **make:cell** Fixed generating view files as classes.
- **make:cell** Fixed treatment of single word class input for case-insensitive OS.

See the repo's
`CHANGELOG.md <https://github.com/codeigniter4/CodeIgniter4/blob/develop/CHANGELOG.md>`_
Expand Down
3 changes: 1 addition & 2 deletions user_guide_src/source/cli/cli_generators.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,12 +59,11 @@ Usage:

Argument:
=========
* ``name``: The name of the cell class. It should be in PascalCase.
* ``name``: The name of the cell class. It should be in PascalCase. **[REQUIRED]**

Options:
========
* ``--namespace``: Set the root namespace. Defaults to value of ``APP_NAMESPACE``.
* ``--suffix``: Append the component suffix to the generated class name.
* ``--force``: Set this flag to overwrite existing files on destination.

make:command
Expand Down
15 changes: 11 additions & 4 deletions user_guide_src/source/outgoing/view_cells.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -80,7 +80,14 @@ Controlled Cells

.. versionadded:: 4.3.0

Controlled Cells have two primary goals: to make it as fast as possible to build the cell, and provide additional logic and flexibility to your views, if they need it. The class must extend ``CodeIgniter\View\Cells\Cell``. They should have a view file in the same folder. By convention the class name should be PascalCase and the view should be the snake_cased version of the class name. So, for example, if you have a ``MyCell`` class, the view file should be ``my_cell.php``.
Controlled cells have two primary goals: to make it as fast as possible to build the cell, and provide additional logic and
flexibility to your views, if they need it. The class must extend ``CodeIgniter\View\Cells\Cell``. They should have a view file
in the same folder. By convention, the class name should be in PascalCase suffixed with ``Cell`` and the view should be
the snake_cased version of the class name, without the suffix. For example, if you have a ``MyCell`` class, the view file
should be ``my.php``.

.. note:: Prior to v4.3.5, the generated view file ends with ``_cell.php``. Though v4.3.5 and newer will generate view files
without the ``_cell`` suffix, existing view files will still be located and loaded.

Creating a Controlled Cell
==========================
Expand All@@ -99,7 +106,7 @@ At the most basic level, all you need to implement within the class are public p
public $message;
}

// app/Cells/alert_message_cell.php
// app/Cells/alert_message.php
<div class="alert alert-<?= esc($type, 'attr') ?>">
<?= esc($message) ?>
</div>
Expand DownExpand Up@@ -199,7 +206,7 @@ If you need to perform additional logic for one or more properties you can use c
}
}

// app/Cells/alert_message_cell.php
// app/Cells/alert_message.php
<div>
<p>type - <?= esc($type) ?></p>
<p>message - <?= esc($message) ?></p>
Expand DownExpand Up@@ -230,7 +237,7 @@ Sometimes you need to perform additional logic for the view, but you don't want
}
}

// app/Cells/recent_posts_cell.php
// app/Cells/recent_posts.php
<ul>
<?php foreach ($posts as $post): ?>
<li><?= $this->linkPost($post) ?></li>
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/Config/Generators.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,7 @@ class Generators extends BaseConfig
*/
public array $views = [
'make:cell' => 'CodeIgniter\Commands\Generators\Views\cell.tpl.php',
'make:cell_view' => 'CodeIgniter\Commands\Generators\Views\cell_view.tpl.php',
'make:command' => 'CodeIgniter\Commands\Generators\Views\command.tpl.php',
'make:config' => 'CodeIgniter\Commands\Generators\Views\config.tpl.php',
'make:controller' => 'CodeIgniter\Commands\Generators\Views\controller.tpl.php',
Expand Down
6 changes: 3 additions & 3 deletions system/CLI/GeneratorTrait.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -235,15 +235,15 @@ protected function qualifyClassName(): string
$component = singular($this->component);

/**
* @see https://regex101.com/r/a5KNCR/1
* @see https://regex101.com/r/a5KNCR/2
*/
$pattern = sprintf('/([a-z][a-z0-9_\/\\\\]+)(%s)/i', $component);
$pattern = sprintf('/([a-z][a-z0-9_\/\\\\]+)(%s)$/i', $component);

if (preg_match($pattern, $class, $matches) === 1) {
$class = $matches[1] . ucfirst($matches[2]);
}

if ($this->enabledSuffixing && $this->getOption('suffix') && ! strripos($class, $component)) {
if ($this->enabledSuffixing && $this->getOption('suffix') && preg_match($pattern, $class) !== 1) {
$class .= ucfirst($component);
}

Expand Down
28 changes: 13 additions & 15 deletions system/Commands/Generators/CellGenerator.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,7 +65,6 @@ class CellGenerator extends BaseCommand
*/
protected $options = [
'--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".',
'--suffix' => 'Append the component title to the class name (e.g. User => UserCell).',
'--force' => 'Force overwrite existing file.',
];

Expand All@@ -74,27 +73,26 @@ class CellGenerator extends BaseCommand
*/
public function run(array $params)
{
// Generate the Class first
$this->component = 'Cell';
$this->directory = 'Cells';
$this->component = 'Cell';
$this->directory = 'Cells';

$params = array_merge($params, ['suffix' => null]);

$this->template = 'cell.tpl.php';
$this->classNameLang = 'CLI.generator.className.cell';

$this->generateClass($params);

// Generate the View
$this->name = 'make:cell_view';
$this->template = 'cell_view.tpl.php';
$this->classNameLang = 'CLI.generator.viewName.cell';

// Form the view name
$segments = explode('\\', $this->qualifyClassName());

$view = array_pop($segments);
$view = decamelize($view);
$segments[] = $view;
$view = implode('\\', $segments);
$className = $this->qualifyClassName();
$viewName = decamelize(class_basename($className));
$viewName = preg_replace('/([a-z][a-z0-9_\/\\\\]+)(_cell)$/i', '$1', $viewName) ?? $viewName;
$namespace = substr($className, 0, strrpos($className, '\\') + 1);

$this->template = 'cell_view.tpl.php';
$this->generateView($namespace . $viewName, $params);

$this->generateView($view, $params);
return 0;
}
}
49 changes: 32 additions & 17 deletions system/View/Cells/Cell.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@
namespace CodeIgniter\View\Cells;

use CodeIgniter\Traits\PropertiesTrait;
use LogicException;
use ReflectionClass;

/**
Expand DownExpand Up@@ -64,37 +65,51 @@ public function setView(string $view)
* from within the view, this method extracts $data into the
* current scope and captures the output buffer instead of
* relying on the view service.
*
* @throws LogicException
*/
final protected function view(?string $view, array $data = []): string
{
$properties = $this->getPublicProperties();
$properties = $this->includeComputedProperties($properties);
$properties = array_merge($properties, $data);

// If no view is specified, we'll try to guess it based on the class name.
if (empty($view)) {
// According to the docs, the name of the view file should be the
// snake_cased version of the cell's class name, but for backward
// compatibility, the name also accepts '_cell' being omitted.
$ref = new ReflectionClass($this);
$view = decamelize($ref->getShortName());
$viewPath = dirname($ref->getFileName()) . DIRECTORY_SEPARATOR . $view . '.php';
$view = is_file($viewPath) ? $viewPath : str_replace('_cell', '', $view);
$view = (string) $view;

if ($view === '') {
$viewName = decamelize(class_basename(static::class));
$directory = dirname((new ReflectionClass($this))->getFileName()) . DIRECTORY_SEPARATOR;

$possibleView1 = $directory . substr($viewName, 0, strrpos($viewName, '_cell')) . '.php';
$possibleView2 = $directory . $viewName . '.php';
}

// Locate our view, preferring the directory of the class.
if (! is_file($view)) {
// Get the local pathname of the Cell
$ref = new ReflectionClass($this);
$view = dirname($ref->getFileName()) . DIRECTORY_SEPARATOR . $view . '.php';
if ($view !== '' && ! is_file($view)) {
$directory = dirname((new ReflectionClass($this))->getFileName()) . DIRECTORY_SEPARATOR;

$view = $directory . $view . '.php';
}

return (function () use ($properties, $view): string {
$candidateViews = array_filter(
[$view, $possibleView1 ?? '', $possibleView2 ?? ''],
static fn (string $path): bool => $path !== '' && is_file($path)
);

if ($candidateViews === []) {
throw new LogicException(sprintf(
'Cannot locate the view file for the "%s" cell.',
static::class
));
}

$foundView = current($candidateViews);

return (function () use ($properties, $foundView): string {
extract($properties);
ob_start();
include $view;
include $foundView;

return ob_get_clean() ?: '';
return ob_get_clean();
})();
}

Expand Down
18 changes: 18 additions & 0 deletions tests/_support/View/Cells/BadCell.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
<?php

/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace Tests\Support\View\Cells;

use CodeIgniter\View\Cells\Cell;

final class BadCell extends Cell
{
}
39 changes: 29 additions & 10 deletions tests/system/Commands/CellGeneratorTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -46,35 +46,54 @@ protected function getFileContents(string $filepath): string
return file_get_contents($filepath) ?: '';
}

public function testGenerateCell()
public function testGenerateCell(): void
{
command('make:cell RecentCell');

// Check the class was generated
$file = APPPATH . 'Cells/RecentCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$contents = $this->getFileContents($file);
$this->assertStringContainsString('class RecentCell extends Cell', $contents);
$this->assertStringContainsString('class RecentCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/recent_cell.php';
$this->assertStringContainsString('File created: ', $this->getStreamFilterBuffer());
$file = APPPATH . 'Cells/recent.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}

public function testGenerateCellSimpleName()
public function testGenerateCellSimpleName(): void
{
command('make:cell Another');

// Check the class was generated
$file = APPPATH . 'Cells/Another.php';
$file = APPPATH . 'Cells/AnotherCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$contents = $this->getFileContents($file);
$this->assertStringContainsString('class Another extends Cell', $contents);
$this->assertStringContainsString('class AnotherCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/another.php';
$this->assertStringContainsString('File created: ', $this->getStreamFilterBuffer());
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}

public function testGenerateCellWithCellInBetween(): void
{
command('make:cell PippoCellular');

// Check the class was generated
$file = APPPATH . 'Cells/PippoCellularCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertStringContainsString('class PippoCellularCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/pippo_cellular.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}
}
10 changes: 10 additions & 0 deletions tests/system/View/ControlledCellTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,8 +13,10 @@

use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\View\Exceptions\ViewException;
use LogicException;
use Tests\Support\View\Cells\AdditionCell;
use Tests\Support\View\Cells\AwesomeCell;
use Tests\Support\View\Cells\BadCell;
use Tests\Support\View\Cells\ColorsCell;
use Tests\Support\View\Cells\GreetingCell;
use Tests\Support\View\Cells\ListerCell;
Expand DownExpand Up@@ -65,6 +67,14 @@ public function testCellThroughRenderMethodWithExtraData()
$this->assertStringContainsString('42, 23, 16, 15, 8, 4', $result);
}

public function testCellThrowsExceptionWhenCannotFindTheViewFile()
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage('Cannot locate the view file for the "Tests\\Support\\View\\Cells\\BadCell" cell.');

view_cell(BadCell::class);
}

public function testCellWithParameters()
{
$result = view_cell(GreetingCell::class, 'greeting=Hi, name=CodeIgniter');
Expand Down
8 changes: 8 additions & 0 deletions user_guide_src/source/changelogs/v4.3.5.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,13 +18,21 @@ Message Changes
Changes
*******

- **make:cell** When creating a new cell, the controller would always have the ``Cell`` suffixed to the class name.
For the view file, the final ``_cell`` is always removed.
- **Cells** For compatibility with previous versions, view filenames ending with ``_cell`` can still be
located by the ``Cell`` as long as auto-detection of view file is enabled (via setting the ``$view`` property
to an empty string).

Deprecations
************

Bugs Fixed
**********

- **Validation:** Fixed a bug where a closure used in combination with ``permit_empty`` or ``if_exist`` rules was causing an error.
- **make:cell** Fixed generating view files as classes.
- **make:cell** Fixed treatment of single word class input for case-insensitive OS.

See the repo's
`CHANGELOG.md <https://github.com/codeigniter4/CodeIgniter4/blob/develop/CHANGELOG.md>`_
Expand Down
3 changes: 1 addition & 2 deletions user_guide_src/source/cli/cli_generators.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,12 +59,11 @@ Usage:

Argument:
=========
* ``name``: The name of the cell class. It should be in PascalCase.
* ``name``: The name of the cell class. It should be in PascalCase. **[REQUIRED]**

Options:
========
* ``--namespace``: Set the root namespace. Defaults to value of ``APP_NAMESPACE``.
* ``--suffix``: Append the component suffix to the generated class name.
* ``--force``: Set this flag to overwrite existing files on destination.

make:command
Expand Down
15 changes: 11 additions & 4 deletions user_guide_src/source/outgoing/view_cells.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -80,7 +80,14 @@ Controlled Cells

.. versionadded:: 4.3.0

Controlled Cells have two primary goals: to make it as fast as possible to build the cell, and provide additional logic and flexibility to your views, if they need it. The class must extend ``CodeIgniter\View\Cells\Cell``. They should have a view file in the same folder. By convention the class name should be PascalCase and the view should be the snake_cased version of the class name. So, for example, if you have a ``MyCell`` class, the view file should be ``my_cell.php``.
Controlled cells have two primary goals: to make it as fast as possible to build the cell, and provide additional logic and
flexibility to your views, if they need it. The class must extend ``CodeIgniter\View\Cells\Cell``. They should have a view file
in the same folder. By convention, the class name should be in PascalCase suffixed with ``Cell`` and the view should be
the snake_cased version of the class name, without the suffix. For example, if you have a ``MyCell`` class, the view file
should be ``my.php``.

.. note:: Prior to v4.3.5, the generated view file ends with ``_cell.php``. Though v4.3.5 and newer will generate view files
without the ``_cell`` suffix, existing view files will still be located and loaded.

Creating a Controlled Cell
==========================
Expand All@@ -99,7 +106,7 @@ At the most basic level, all you need to implement within the class are public p
public $message;
}

// app/Cells/alert_message_cell.php
// app/Cells/alert_message.php
<div class="alert alert-<?= esc($type, 'attr') ?>">
<?= esc($message) ?>
</div>
Expand DownExpand Up@@ -199,7 +206,7 @@ If you need to perform additional logic for one or more properties you can use c
}
}

// app/Cells/alert_message_cell.php
// app/Cells/alert_message.php
<div>
<p>type - <?= esc($type) ?></p>
<p>message - <?= esc($message) ?></p>
Expand DownExpand Up@@ -230,7 +237,7 @@ Sometimes you need to perform additional logic for the view, but you don't want
}
}

// app/Cells/recent_posts_cell.php
// app/Cells/recent_posts.php
<ul>
<?php foreach ($posts as $post): ?>
<li><?= $this->linkPost($post) ?></li>
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/Config/Generators.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,7 @@ class Generators extends BaseConfig
*/
public array $views = [
'make:cell' => 'CodeIgniter\Commands\Generators\Views\cell.tpl.php',
'make:cell_view' => 'CodeIgniter\Commands\Generators\Views\cell_view.tpl.php',
'make:command' => 'CodeIgniter\Commands\Generators\Views\command.tpl.php',
'make:config' => 'CodeIgniter\Commands\Generators\Views\config.tpl.php',
'make:controller' => 'CodeIgniter\Commands\Generators\Views\controller.tpl.php',
Expand Down
6 changes: 3 additions & 3 deletions system/CLI/GeneratorTrait.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -235,15 +235,15 @@ protected function qualifyClassName(): string
$component = singular($this->component);

/**
* @see https://regex101.com/r/a5KNCR/1
* @see https://regex101.com/r/a5KNCR/2
*/
$pattern = sprintf('/([a-z][a-z0-9_\/\\\\]+)(%s)/i', $component);
$pattern = sprintf('/([a-z][a-z0-9_\/\\\\]+)(%s)$/i', $component);

if (preg_match($pattern, $class, $matches) === 1) {
$class = $matches[1] . ucfirst($matches[2]);
}

if ($this->enabledSuffixing && $this->getOption('suffix') && ! strripos($class, $component)) {
if ($this->enabledSuffixing && $this->getOption('suffix') && preg_match($pattern, $class) !== 1) {
$class .= ucfirst($component);
}

Expand Down
28 changes: 13 additions & 15 deletions system/Commands/Generators/CellGenerator.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,7 +65,6 @@ class CellGenerator extends BaseCommand
*/
protected $options = [
'--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".',
'--suffix' => 'Append the component title to the class name (e.g. User => UserCell).',
'--force' => 'Force overwrite existing file.',
];

Expand All@@ -74,27 +73,26 @@ class CellGenerator extends BaseCommand
*/
public function run(array $params)
{
// Generate the Class first
$this->component = 'Cell';
$this->directory = 'Cells';
$this->component = 'Cell';
$this->directory = 'Cells';

$params = array_merge($params, ['suffix' => null]);

$this->template = 'cell.tpl.php';
$this->classNameLang = 'CLI.generator.className.cell';

$this->generateClass($params);

// Generate the View
$this->name = 'make:cell_view';
$this->template = 'cell_view.tpl.php';
$this->classNameLang = 'CLI.generator.viewName.cell';

// Form the view name
$segments = explode('\\', $this->qualifyClassName());

$view = array_pop($segments);
$view = decamelize($view);
$segments[] = $view;
$view = implode('\\', $segments);
$className = $this->qualifyClassName();
$viewName = decamelize(class_basename($className));
$viewName = preg_replace('/([a-z][a-z0-9_\/\\\\]+)(_cell)$/i', '$1', $viewName) ?? $viewName;
$namespace = substr($className, 0, strrpos($className, '\\') + 1);

$this->template = 'cell_view.tpl.php';
$this->generateView($namespace . $viewName, $params);

$this->generateView($view, $params);
return 0;
}
}
49 changes: 32 additions & 17 deletions system/View/Cells/Cell.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@
namespace CodeIgniter\View\Cells;

use CodeIgniter\Traits\PropertiesTrait;
use LogicException;
use ReflectionClass;

/**
Expand DownExpand Up@@ -64,37 +65,51 @@ public function setView(string $view)
* from within the view, this method extracts $data into the
* current scope and captures the output buffer instead of
* relying on the view service.
*
* @throws LogicException
*/
final protected function view(?string $view, array $data = []): string
{
$properties = $this->getPublicProperties();
$properties = $this->includeComputedProperties($properties);
$properties = array_merge($properties, $data);

// If no view is specified, we'll try to guess it based on the class name.
if (empty($view)) {
// According to the docs, the name of the view file should be the
// snake_cased version of the cell's class name, but for backward
// compatibility, the name also accepts '_cell' being omitted.
$ref = new ReflectionClass($this);
$view = decamelize($ref->getShortName());
$viewPath = dirname($ref->getFileName()) . DIRECTORY_SEPARATOR . $view . '.php';
$view = is_file($viewPath) ? $viewPath : str_replace('_cell', '', $view);
$view = (string) $view;

if ($view === '') {
$viewName = decamelize(class_basename(static::class));
$directory = dirname((new ReflectionClass($this))->getFileName()) . DIRECTORY_SEPARATOR;

$possibleView1 = $directory . substr($viewName, 0, strrpos($viewName, '_cell')) . '.php';
$possibleView2 = $directory . $viewName . '.php';
}

// Locate our view, preferring the directory of the class.
if (! is_file($view)) {
// Get the local pathname of the Cell
$ref = new ReflectionClass($this);
$view = dirname($ref->getFileName()) . DIRECTORY_SEPARATOR . $view . '.php';
if ($view !== '' && ! is_file($view)) {
$directory = dirname((new ReflectionClass($this))->getFileName()) . DIRECTORY_SEPARATOR;

$view = $directory . $view . '.php';
}

return (function () use ($properties, $view): string {
$candidateViews = array_filter(
[$view, $possibleView1 ?? '', $possibleView2 ?? ''],
static fn (string $path): bool => $path !== '' && is_file($path)
);

if ($candidateViews === []) {
throw new LogicException(sprintf(
'Cannot locate the view file for the "%s" cell.',
static::class
));
}

$foundView = current($candidateViews);

return (function () use ($properties, $foundView): string {
extract($properties);
ob_start();
include $view;
include $foundView;

return ob_get_clean() ?: '';
return ob_get_clean();
})();
}

Expand Down
18 changes: 18 additions & 0 deletions tests/_support/View/Cells/BadCell.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
<?php

/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace Tests\Support\View\Cells;

use CodeIgniter\View\Cells\Cell;

final class BadCell extends Cell
{
}
39 changes: 29 additions & 10 deletions tests/system/Commands/CellGeneratorTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -46,35 +46,54 @@ protected function getFileContents(string $filepath): string
return file_get_contents($filepath) ?: '';
}

public function testGenerateCell()
public function testGenerateCell(): void
{
command('make:cell RecentCell');

// Check the class was generated
$file = APPPATH . 'Cells/RecentCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$contents = $this->getFileContents($file);
$this->assertStringContainsString('class RecentCell extends Cell', $contents);
$this->assertStringContainsString('class RecentCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/recent_cell.php';
$this->assertStringContainsString('File created: ', $this->getStreamFilterBuffer());
$file = APPPATH . 'Cells/recent.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}

public function testGenerateCellSimpleName()
public function testGenerateCellSimpleName(): void
{
command('make:cell Another');

// Check the class was generated
$file = APPPATH . 'Cells/Another.php';
$file = APPPATH . 'Cells/AnotherCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$contents = $this->getFileContents($file);
$this->assertStringContainsString('class Another extends Cell', $contents);
$this->assertStringContainsString('class AnotherCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/another.php';
$this->assertStringContainsString('File created: ', $this->getStreamFilterBuffer());
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}

public function testGenerateCellWithCellInBetween(): void
{
command('make:cell PippoCellular');

// Check the class was generated
$file = APPPATH . 'Cells/PippoCellularCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertStringContainsString('class PippoCellularCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/pippo_cellular.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}
}
10 changes: 10 additions & 0 deletions tests/system/View/ControlledCellTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,8 +13,10 @@

use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\View\Exceptions\ViewException;
use LogicException;
use Tests\Support\View\Cells\AdditionCell;
use Tests\Support\View\Cells\AwesomeCell;
use Tests\Support\View\Cells\BadCell;
use Tests\Support\View\Cells\ColorsCell;
use Tests\Support\View\Cells\GreetingCell;
use Tests\Support\View\Cells\ListerCell;
Expand DownExpand Up@@ -65,6 +67,14 @@ public function testCellThroughRenderMethodWithExtraData()
$this->assertStringContainsString('42, 23, 16, 15, 8, 4', $result);
}

public function testCellThrowsExceptionWhenCannotFindTheViewFile()
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage('Cannot locate the view file for the "Tests\\Support\\View\\Cells\\BadCell" cell.');

view_cell(BadCell::class);
}

public function testCellWithParameters()
{
$result = view_cell(GreetingCell::class, 'greeting=Hi, name=CodeIgniter');
Expand Down
8 changes: 8 additions & 0 deletions user_guide_src/source/changelogs/v4.3.5.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,13 +18,21 @@ Message Changes
Changes
*******

- **make:cell** When creating a new cell, the controller would always have the ``Cell`` suffixed to the class name.
For the view file, the final ``_cell`` is always removed.
- **Cells** For compatibility with previous versions, view filenames ending with ``_cell`` can still be
located by the ``Cell`` as long as auto-detection of view file is enabled (via setting the ``$view`` property
to an empty string).

Deprecations
************

Bugs Fixed
**********

- **Validation:** Fixed a bug where a closure used in combination with ``permit_empty`` or ``if_exist`` rules was causing an error.
- **make:cell** Fixed generating view files as classes.
- **make:cell** Fixed treatment of single word class input for case-insensitive OS.

See the repo's
`CHANGELOG.md <https://github.com/codeigniter4/CodeIgniter4/blob/develop/CHANGELOG.md>`_
Expand Down
3 changes: 1 addition & 2 deletions user_guide_src/source/cli/cli_generators.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,12 +59,11 @@ Usage:

Argument:
=========
* ``name``: The name of the cell class. It should be in PascalCase.
* ``name``: The name of the cell class. It should be in PascalCase. **[REQUIRED]**

Options:
========
* ``--namespace``: Set the root namespace. Defaults to value of ``APP_NAMESPACE``.
* ``--suffix``: Append the component suffix to the generated class name.
* ``--force``: Set this flag to overwrite existing files on destination.

make:command
Expand Down
15 changes: 11 additions & 4 deletions user_guide_src/source/outgoing/view_cells.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -80,7 +80,14 @@ Controlled Cells

.. versionadded:: 4.3.0

Controlled Cells have two primary goals: to make it as fast as possible to build the cell, and provide additional logic and flexibility to your views, if they need it. The class must extend ``CodeIgniter\View\Cells\Cell``. They should have a view file in the same folder. By convention the class name should be PascalCase and the view should be the snake_cased version of the class name. So, for example, if you have a ``MyCell`` class, the view file should be ``my_cell.php``.
Controlled cells have two primary goals: to make it as fast as possible to build the cell, and provide additional logic and
flexibility to your views, if they need it. The class must extend ``CodeIgniter\View\Cells\Cell``. They should have a view file
in the same folder. By convention, the class name should be in PascalCase suffixed with ``Cell`` and the view should be
the snake_cased version of the class name, without the suffix. For example, if you have a ``MyCell`` class, the view file
should be ``my.php``.

.. note:: Prior to v4.3.5, the generated view file ends with ``_cell.php``. Though v4.3.5 and newer will generate view files
without the ``_cell`` suffix, existing view files will still be located and loaded.

Creating a Controlled Cell
==========================
Expand All@@ -99,7 +106,7 @@ At the most basic level, all you need to implement within the class are public p
public $message;
}

// app/Cells/alert_message_cell.php
// app/Cells/alert_message.php
<div class="alert alert-<?= esc($type, 'attr') ?>">
<?= esc($message) ?>
</div>
Expand DownExpand Up@@ -199,7 +206,7 @@ If you need to perform additional logic for one or more properties you can use c
}
}

// app/Cells/alert_message_cell.php
// app/Cells/alert_message.php
<div>
<p>type - <?= esc($type) ?></p>
<p>message - <?= esc($message) ?></p>
Expand DownExpand Up@@ -230,7 +237,7 @@ Sometimes you need to perform additional logic for the view, but you don't want
}
}

// app/Cells/recent_posts_cell.php
// app/Cells/recent_posts.php
<ul>
<?php foreach ($posts as $post): ?>
<li><?= $this->linkPost($post) ?></li>
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/Config/Generators.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,7 @@ class Generators extends BaseConfig
*/
public array $views = [
'make:cell' => 'CodeIgniter\Commands\Generators\Views\cell.tpl.php',
'make:cell_view' => 'CodeIgniter\Commands\Generators\Views\cell_view.tpl.php',
'make:command' => 'CodeIgniter\Commands\Generators\Views\command.tpl.php',
'make:config' => 'CodeIgniter\Commands\Generators\Views\config.tpl.php',
'make:controller' => 'CodeIgniter\Commands\Generators\Views\controller.tpl.php',
Expand Down
6 changes: 3 additions & 3 deletions system/CLI/GeneratorTrait.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -235,15 +235,15 @@ protected function qualifyClassName(): string
$component = singular($this->component);

/**
* @see https://regex101.com/r/a5KNCR/1
* @see https://regex101.com/r/a5KNCR/2
*/
$pattern = sprintf('/([a-z][a-z0-9_\/\\\\]+)(%s)/i', $component);
$pattern = sprintf('/([a-z][a-z0-9_\/\\\\]+)(%s)$/i', $component);

if (preg_match($pattern, $class, $matches) === 1) {
$class = $matches[1] . ucfirst($matches[2]);
}

if ($this->enabledSuffixing && $this->getOption('suffix') && ! strripos($class, $component)) {
if ($this->enabledSuffixing && $this->getOption('suffix') && preg_match($pattern, $class) !== 1) {
$class .= ucfirst($component);
}

Expand Down
28 changes: 13 additions & 15 deletions system/Commands/Generators/CellGenerator.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,7 +65,6 @@ class CellGenerator extends BaseCommand
*/
protected $options = [
'--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".',
'--suffix' => 'Append the component title to the class name (e.g. User => UserCell).',
'--force' => 'Force overwrite existing file.',
];

Expand All@@ -74,27 +73,26 @@ class CellGenerator extends BaseCommand
*/
public function run(array $params)
{
// Generate the Class first
$this->component = 'Cell';
$this->directory = 'Cells';
$this->component = 'Cell';
$this->directory = 'Cells';

$params = array_merge($params, ['suffix' => null]);

$this->template = 'cell.tpl.php';
$this->classNameLang = 'CLI.generator.className.cell';

$this->generateClass($params);

// Generate the View
$this->name = 'make:cell_view';
$this->template = 'cell_view.tpl.php';
$this->classNameLang = 'CLI.generator.viewName.cell';

// Form the view name
$segments = explode('\\', $this->qualifyClassName());

$view = array_pop($segments);
$view = decamelize($view);
$segments[] = $view;
$view = implode('\\', $segments);
$className = $this->qualifyClassName();
$viewName = decamelize(class_basename($className));
$viewName = preg_replace('/([a-z][a-z0-9_\/\\\\]+)(_cell)$/i', '$1', $viewName) ?? $viewName;
$namespace = substr($className, 0, strrpos($className, '\\') + 1);

$this->template = 'cell_view.tpl.php';
$this->generateView($namespace . $viewName, $params);

$this->generateView($view, $params);
return 0;
}
}
49 changes: 32 additions & 17 deletions system/View/Cells/Cell.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@
namespace CodeIgniter\View\Cells;

use CodeIgniter\Traits\PropertiesTrait;
use LogicException;
use ReflectionClass;

/**
Expand DownExpand Up@@ -64,37 +65,51 @@ public function setView(string $view)
* from within the view, this method extracts $data into the
* current scope and captures the output buffer instead of
* relying on the view service.
*
* @throws LogicException
*/
final protected function view(?string $view, array $data = []): string
{
$properties = $this->getPublicProperties();
$properties = $this->includeComputedProperties($properties);
$properties = array_merge($properties, $data);

// If no view is specified, we'll try to guess it based on the class name.
if (empty($view)) {
// According to the docs, the name of the view file should be the
// snake_cased version of the cell's class name, but for backward
// compatibility, the name also accepts '_cell' being omitted.
$ref = new ReflectionClass($this);
$view = decamelize($ref->getShortName());
$viewPath = dirname($ref->getFileName()) . DIRECTORY_SEPARATOR . $view . '.php';
$view = is_file($viewPath) ? $viewPath : str_replace('_cell', '', $view);
$view = (string) $view;

if ($view === '') {
$viewName = decamelize(class_basename(static::class));
$directory = dirname((new ReflectionClass($this))->getFileName()) . DIRECTORY_SEPARATOR;

$possibleView1 = $directory . substr($viewName, 0, strrpos($viewName, '_cell')) . '.php';
$possibleView2 = $directory . $viewName . '.php';
}

// Locate our view, preferring the directory of the class.
if (! is_file($view)) {
// Get the local pathname of the Cell
$ref = new ReflectionClass($this);
$view = dirname($ref->getFileName()) . DIRECTORY_SEPARATOR . $view . '.php';
if ($view !== '' && ! is_file($view)) {
$directory = dirname((new ReflectionClass($this))->getFileName()) . DIRECTORY_SEPARATOR;

$view = $directory . $view . '.php';
}

return (function () use ($properties, $view): string {
$candidateViews = array_filter(
[$view, $possibleView1 ?? '', $possibleView2 ?? ''],
static fn (string $path): bool => $path !== '' && is_file($path)
);

if ($candidateViews === []) {
throw new LogicException(sprintf(
'Cannot locate the view file for the "%s" cell.',
static::class
));
}

$foundView = current($candidateViews);

return (function () use ($properties, $foundView): string {
extract($properties);
ob_start();
include $view;
include $foundView;

return ob_get_clean() ?: '';
return ob_get_clean();
})();
}

Expand Down
18 changes: 18 additions & 0 deletions tests/_support/View/Cells/BadCell.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
<?php

/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace Tests\Support\View\Cells;

use CodeIgniter\View\Cells\Cell;

final class BadCell extends Cell
{
}
39 changes: 29 additions & 10 deletions tests/system/Commands/CellGeneratorTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -46,35 +46,54 @@ protected function getFileContents(string $filepath): string
return file_get_contents($filepath) ?: '';
}

public function testGenerateCell()
public function testGenerateCell(): void
{
command('make:cell RecentCell');

// Check the class was generated
$file = APPPATH . 'Cells/RecentCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$contents = $this->getFileContents($file);
$this->assertStringContainsString('class RecentCell extends Cell', $contents);
$this->assertStringContainsString('class RecentCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/recent_cell.php';
$this->assertStringContainsString('File created: ', $this->getStreamFilterBuffer());
$file = APPPATH . 'Cells/recent.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}

public function testGenerateCellSimpleName()
public function testGenerateCellSimpleName(): void
{
command('make:cell Another');

// Check the class was generated
$file = APPPATH . 'Cells/Another.php';
$file = APPPATH . 'Cells/AnotherCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$contents = $this->getFileContents($file);
$this->assertStringContainsString('class Another extends Cell', $contents);
$this->assertStringContainsString('class AnotherCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/another.php';
$this->assertStringContainsString('File created: ', $this->getStreamFilterBuffer());
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}

public function testGenerateCellWithCellInBetween(): void
{
command('make:cell PippoCellular');

// Check the class was generated
$file = APPPATH . 'Cells/PippoCellularCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertStringContainsString('class PippoCellularCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/pippo_cellular.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}
}
10 changes: 10 additions & 0 deletions tests/system/View/ControlledCellTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,8 +13,10 @@

use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\View\Exceptions\ViewException;
use LogicException;
use Tests\Support\View\Cells\AdditionCell;
use Tests\Support\View\Cells\AwesomeCell;
use Tests\Support\View\Cells\BadCell;
use Tests\Support\View\Cells\ColorsCell;
use Tests\Support\View\Cells\GreetingCell;
use Tests\Support\View\Cells\ListerCell;
Expand DownExpand Up@@ -65,6 +67,14 @@ public function testCellThroughRenderMethodWithExtraData()
$this->assertStringContainsString('42, 23, 16, 15, 8, 4', $result);
}

public function testCellThrowsExceptionWhenCannotFindTheViewFile()
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage('Cannot locate the view file for the "Tests\\Support\\View\\Cells\\BadCell" cell.');

view_cell(BadCell::class);
}

public function testCellWithParameters()
{
$result = view_cell(GreetingCell::class, 'greeting=Hi, name=CodeIgniter');
Expand Down
8 changes: 8 additions & 0 deletions user_guide_src/source/changelogs/v4.3.5.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,13 +18,21 @@ Message Changes
Changes
*******

- **make:cell** When creating a new cell, the controller would always have the ``Cell`` suffixed to the class name.
For the view file, the final ``_cell`` is always removed.
- **Cells** For compatibility with previous versions, view filenames ending with ``_cell`` can still be
located by the ``Cell`` as long as auto-detection of view file is enabled (via setting the ``$view`` property
to an empty string).

Deprecations
************

Bugs Fixed
**********

- **Validation:** Fixed a bug where a closure used in combination with ``permit_empty`` or ``if_exist`` rules was causing an error.
- **make:cell** Fixed generating view files as classes.
- **make:cell** Fixed treatment of single word class input for case-insensitive OS.

See the repo's
`CHANGELOG.md <https://github.com/codeigniter4/CodeIgniter4/blob/develop/CHANGELOG.md>`_
Expand Down
3 changes: 1 addition & 2 deletions user_guide_src/source/cli/cli_generators.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,12 +59,11 @@ Usage:

Argument:
=========
* ``name``: The name of the cell class. It should be in PascalCase.
* ``name``: The name of the cell class. It should be in PascalCase. **[REQUIRED]**

Options:
========
* ``--namespace``: Set the root namespace. Defaults to value of ``APP_NAMESPACE``.
* ``--suffix``: Append the component suffix to the generated class name.
* ``--force``: Set this flag to overwrite existing files on destination.

make:command
Expand Down
15 changes: 11 additions & 4 deletions user_guide_src/source/outgoing/view_cells.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -80,7 +80,14 @@ Controlled Cells

.. versionadded:: 4.3.0

Controlled Cells have two primary goals: to make it as fast as possible to build the cell, and provide additional logic and flexibility to your views, if they need it. The class must extend ``CodeIgniter\View\Cells\Cell``. They should have a view file in the same folder. By convention the class name should be PascalCase and the view should be the snake_cased version of the class name. So, for example, if you have a ``MyCell`` class, the view file should be ``my_cell.php``.
Controlled cells have two primary goals: to make it as fast as possible to build the cell, and provide additional logic and
flexibility to your views, if they need it. The class must extend ``CodeIgniter\View\Cells\Cell``. They should have a view file
in the same folder. By convention, the class name should be in PascalCase suffixed with ``Cell`` and the view should be
the snake_cased version of the class name, without the suffix. For example, if you have a ``MyCell`` class, the view file
should be ``my.php``.

.. note:: Prior to v4.3.5, the generated view file ends with ``_cell.php``. Though v4.3.5 and newer will generate view files
without the ``_cell`` suffix, existing view files will still be located and loaded.

Creating a Controlled Cell
==========================
Expand All@@ -99,7 +106,7 @@ At the most basic level, all you need to implement within the class are public p
public $message;
}

// app/Cells/alert_message_cell.php
// app/Cells/alert_message.php
<div class="alert alert-<?= esc($type, 'attr') ?>">
<?= esc($message) ?>
</div>
Expand DownExpand Up@@ -199,7 +206,7 @@ If you need to perform additional logic for one or more properties you can use c
}
}

// app/Cells/alert_message_cell.php
// app/Cells/alert_message.php
<div>
<p>type - <?= esc($type) ?></p>
<p>message - <?= esc($message) ?></p>
Expand DownExpand Up@@ -230,7 +237,7 @@ Sometimes you need to perform additional logic for the view, but you don't want
}
}

// app/Cells/recent_posts_cell.php
// app/Cells/recent_posts.php
<ul>
<?php foreach ($posts as $post): ?>
<li><?= $this->linkPost($post) ?></li>
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/Config/Generators.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,7 @@ class Generators extends BaseConfig
*/
public array $views = [
'make:cell' => 'CodeIgniter\Commands\Generators\Views\cell.tpl.php',
'make:cell_view' => 'CodeIgniter\Commands\Generators\Views\cell_view.tpl.php',
'make:command' => 'CodeIgniter\Commands\Generators\Views\command.tpl.php',
'make:config' => 'CodeIgniter\Commands\Generators\Views\config.tpl.php',
'make:controller' => 'CodeIgniter\Commands\Generators\Views\controller.tpl.php',
Expand Down
6 changes: 3 additions & 3 deletions system/CLI/GeneratorTrait.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -235,15 +235,15 @@ protected function qualifyClassName(): string
$component = singular($this->component);

/**
* @see https://regex101.com/r/a5KNCR/1
* @see https://regex101.com/r/a5KNCR/2
*/
$pattern = sprintf('/([a-z][a-z0-9_\/\\\\]+)(%s)/i', $component);
$pattern = sprintf('/([a-z][a-z0-9_\/\\\\]+)(%s)$/i', $component);

if (preg_match($pattern, $class, $matches) === 1) {
$class = $matches[1] . ucfirst($matches[2]);
}

if ($this->enabledSuffixing && $this->getOption('suffix') && ! strripos($class, $component)) {
if ($this->enabledSuffixing && $this->getOption('suffix') && preg_match($pattern, $class) !== 1) {
$class .= ucfirst($component);
}

Expand Down
28 changes: 13 additions & 15 deletions system/Commands/Generators/CellGenerator.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,7 +65,6 @@ class CellGenerator extends BaseCommand
*/
protected $options = [
'--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".',
'--suffix' => 'Append the component title to the class name (e.g. User => UserCell).',
'--force' => 'Force overwrite existing file.',
];

Expand All@@ -74,27 +73,26 @@ class CellGenerator extends BaseCommand
*/
public function run(array $params)
{
// Generate the Class first
$this->component = 'Cell';
$this->directory = 'Cells';
$this->component = 'Cell';
$this->directory = 'Cells';

$params = array_merge($params, ['suffix' => null]);

$this->template = 'cell.tpl.php';
$this->classNameLang = 'CLI.generator.className.cell';

$this->generateClass($params);

// Generate the View
$this->name = 'make:cell_view';
$this->template = 'cell_view.tpl.php';
$this->classNameLang = 'CLI.generator.viewName.cell';

// Form the view name
$segments = explode('\\', $this->qualifyClassName());

$view = array_pop($segments);
$view = decamelize($view);
$segments[] = $view;
$view = implode('\\', $segments);
$className = $this->qualifyClassName();
$viewName = decamelize(class_basename($className));
$viewName = preg_replace('/([a-z][a-z0-9_\/\\\\]+)(_cell)$/i', '$1', $viewName) ?? $viewName;
$namespace = substr($className, 0, strrpos($className, '\\') + 1);

$this->template = 'cell_view.tpl.php';
$this->generateView($namespace . $viewName, $params);

$this->generateView($view, $params);
return 0;
}
}
49 changes: 32 additions & 17 deletions system/View/Cells/Cell.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@
namespace CodeIgniter\View\Cells;

use CodeIgniter\Traits\PropertiesTrait;
use LogicException;
use ReflectionClass;

/**
Expand DownExpand Up@@ -64,37 +65,51 @@ public function setView(string $view)
* from within the view, this method extracts $data into the
* current scope and captures the output buffer instead of
* relying on the view service.
*
* @throws LogicException
*/
final protected function view(?string $view, array $data = []): string
{
$properties = $this->getPublicProperties();
$properties = $this->includeComputedProperties($properties);
$properties = array_merge($properties, $data);

// If no view is specified, we'll try to guess it based on the class name.
if (empty($view)) {
// According to the docs, the name of the view file should be the
// snake_cased version of the cell's class name, but for backward
// compatibility, the name also accepts '_cell' being omitted.
$ref = new ReflectionClass($this);
$view = decamelize($ref->getShortName());
$viewPath = dirname($ref->getFileName()) . DIRECTORY_SEPARATOR . $view . '.php';
$view = is_file($viewPath) ? $viewPath : str_replace('_cell', '', $view);
$view = (string) $view;

if ($view === '') {
$viewName = decamelize(class_basename(static::class));
$directory = dirname((new ReflectionClass($this))->getFileName()) . DIRECTORY_SEPARATOR;

$possibleView1 = $directory . substr($viewName, 0, strrpos($viewName, '_cell')) . '.php';
$possibleView2 = $directory . $viewName . '.php';
}

// Locate our view, preferring the directory of the class.
if (! is_file($view)) {
// Get the local pathname of the Cell
$ref = new ReflectionClass($this);
$view = dirname($ref->getFileName()) . DIRECTORY_SEPARATOR . $view . '.php';
if ($view !== '' && ! is_file($view)) {
$directory = dirname((new ReflectionClass($this))->getFileName()) . DIRECTORY_SEPARATOR;

$view = $directory . $view . '.php';
}

return (function () use ($properties, $view): string {
$candidateViews = array_filter(
[$view, $possibleView1 ?? '', $possibleView2 ?? ''],
static fn (string $path): bool => $path !== '' && is_file($path)
);

if ($candidateViews === []) {
throw new LogicException(sprintf(
'Cannot locate the view file for the "%s" cell.',
static::class
));
}

$foundView = current($candidateViews);

return (function () use ($properties, $foundView): string {
extract($properties);
ob_start();
include $view;
include $foundView;

return ob_get_clean() ?: '';
return ob_get_clean();
})();
}

Expand Down
18 changes: 18 additions & 0 deletions tests/_support/View/Cells/BadCell.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
<?php

/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace Tests\Support\View\Cells;

use CodeIgniter\View\Cells\Cell;

final class BadCell extends Cell
{
}
39 changes: 29 additions & 10 deletions tests/system/Commands/CellGeneratorTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -46,35 +46,54 @@ protected function getFileContents(string $filepath): string
return file_get_contents($filepath) ?: '';
}

public function testGenerateCell()
public function testGenerateCell(): void
{
command('make:cell RecentCell');

// Check the class was generated
$file = APPPATH . 'Cells/RecentCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$contents = $this->getFileContents($file);
$this->assertStringContainsString('class RecentCell extends Cell', $contents);
$this->assertStringContainsString('class RecentCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/recent_cell.php';
$this->assertStringContainsString('File created: ', $this->getStreamFilterBuffer());
$file = APPPATH . 'Cells/recent.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}

public function testGenerateCellSimpleName()
public function testGenerateCellSimpleName(): void
{
command('make:cell Another');

// Check the class was generated
$file = APPPATH . 'Cells/Another.php';
$file = APPPATH . 'Cells/AnotherCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$contents = $this->getFileContents($file);
$this->assertStringContainsString('class Another extends Cell', $contents);
$this->assertStringContainsString('class AnotherCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/another.php';
$this->assertStringContainsString('File created: ', $this->getStreamFilterBuffer());
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}

public function testGenerateCellWithCellInBetween(): void
{
command('make:cell PippoCellular');

// Check the class was generated
$file = APPPATH . 'Cells/PippoCellularCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertStringContainsString('class PippoCellularCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/pippo_cellular.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}
}
10 changes: 10 additions & 0 deletions tests/system/View/ControlledCellTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,8 +13,10 @@

use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\View\Exceptions\ViewException;
use LogicException;
use Tests\Support\View\Cells\AdditionCell;
use Tests\Support\View\Cells\AwesomeCell;
use Tests\Support\View\Cells\BadCell;
use Tests\Support\View\Cells\ColorsCell;
use Tests\Support\View\Cells\GreetingCell;
use Tests\Support\View\Cells\ListerCell;
Expand DownExpand Up@@ -65,6 +67,14 @@ public function testCellThroughRenderMethodWithExtraData()
$this->assertStringContainsString('42, 23, 16, 15, 8, 4', $result);
}

public function testCellThrowsExceptionWhenCannotFindTheViewFile()
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage('Cannot locate the view file for the "Tests\\Support\\View\\Cells\\BadCell" cell.');

view_cell(BadCell::class);
}

public function testCellWithParameters()
{
$result = view_cell(GreetingCell::class, 'greeting=Hi, name=CodeIgniter');
Expand Down
8 changes: 8 additions & 0 deletions user_guide_src/source/changelogs/v4.3.5.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,13 +18,21 @@ Message Changes
Changes
*******

- **make:cell** When creating a new cell, the controller would always have the ``Cell`` suffixed to the class name.
For the view file, the final ``_cell`` is always removed.
- **Cells** For compatibility with previous versions, view filenames ending with ``_cell`` can still be
located by the ``Cell`` as long as auto-detection of view file is enabled (via setting the ``$view`` property
to an empty string).

Deprecations
************

Bugs Fixed
**********

- **Validation:** Fixed a bug where a closure used in combination with ``permit_empty`` or ``if_exist`` rules was causing an error.
- **make:cell** Fixed generating view files as classes.
- **make:cell** Fixed treatment of single word class input for case-insensitive OS.

See the repo's
`CHANGELOG.md <https://github.com/codeigniter4/CodeIgniter4/blob/develop/CHANGELOG.md>`_
Expand Down
3 changes: 1 addition & 2 deletions user_guide_src/source/cli/cli_generators.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,12 +59,11 @@ Usage:

Argument:
=========
* ``name``: The name of the cell class. It should be in PascalCase.
* ``name``: The name of the cell class. It should be in PascalCase. **[REQUIRED]**

Options:
========
* ``--namespace``: Set the root namespace. Defaults to value of ``APP_NAMESPACE``.
* ``--suffix``: Append the component suffix to the generated class name.
* ``--force``: Set this flag to overwrite existing files on destination.

make:command
Expand Down
15 changes: 11 additions & 4 deletions user_guide_src/source/outgoing/view_cells.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -80,7 +80,14 @@ Controlled Cells

.. versionadded:: 4.3.0

Controlled Cells have two primary goals: to make it as fast as possible to build the cell, and provide additional logic and flexibility to your views, if they need it. The class must extend ``CodeIgniter\View\Cells\Cell``. They should have a view file in the same folder. By convention the class name should be PascalCase and the view should be the snake_cased version of the class name. So, for example, if you have a ``MyCell`` class, the view file should be ``my_cell.php``.
Controlled cells have two primary goals: to make it as fast as possible to build the cell, and provide additional logic and
flexibility to your views, if they need it. The class must extend ``CodeIgniter\View\Cells\Cell``. They should have a view file
in the same folder. By convention, the class name should be in PascalCase suffixed with ``Cell`` and the view should be
the snake_cased version of the class name, without the suffix. For example, if you have a ``MyCell`` class, the view file
should be ``my.php``.

.. note:: Prior to v4.3.5, the generated view file ends with ``_cell.php``. Though v4.3.5 and newer will generate view files
without the ``_cell`` suffix, existing view files will still be located and loaded.

Creating a Controlled Cell
==========================
Expand All@@ -99,7 +106,7 @@ At the most basic level, all you need to implement within the class are public p
public $message;
}

// app/Cells/alert_message_cell.php
// app/Cells/alert_message.php
<div class="alert alert-<?= esc($type, 'attr') ?>">
<?= esc($message) ?>
</div>
Expand DownExpand Up@@ -199,7 +206,7 @@ If you need to perform additional logic for one or more properties you can use c
}
}

// app/Cells/alert_message_cell.php
// app/Cells/alert_message.php
<div>
<p>type - <?= esc($type) ?></p>
<p>message - <?= esc($message) ?></p>
Expand DownExpand Up@@ -230,7 +237,7 @@ Sometimes you need to perform additional logic for the view, but you don't want
}
}

// app/Cells/recent_posts_cell.php
// app/Cells/recent_posts.php
<ul>
<?php foreach ($posts as $post): ?>
<li><?= $this->linkPost($post) ?></li>
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/Config/Generators.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,7 @@ class Generators extends BaseConfig
*/
public array $views = [
'make:cell' => 'CodeIgniter\Commands\Generators\Views\cell.tpl.php',
'make:cell_view' => 'CodeIgniter\Commands\Generators\Views\cell_view.tpl.php',
'make:command' => 'CodeIgniter\Commands\Generators\Views\command.tpl.php',
'make:config' => 'CodeIgniter\Commands\Generators\Views\config.tpl.php',
'make:controller' => 'CodeIgniter\Commands\Generators\Views\controller.tpl.php',
Expand Down
6 changes: 3 additions & 3 deletions system/CLI/GeneratorTrait.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -235,15 +235,15 @@ protected function qualifyClassName(): string
$component = singular($this->component);

/**
* @see https://regex101.com/r/a5KNCR/1
* @see https://regex101.com/r/a5KNCR/2
*/
$pattern = sprintf('/([a-z][a-z0-9_\/\\\\]+)(%s)/i', $component);
$pattern = sprintf('/([a-z][a-z0-9_\/\\\\]+)(%s)$/i', $component);

if (preg_match($pattern, $class, $matches) === 1) {
$class = $matches[1] . ucfirst($matches[2]);
}

if ($this->enabledSuffixing && $this->getOption('suffix') && ! strripos($class, $component)) {
if ($this->enabledSuffixing && $this->getOption('suffix') && preg_match($pattern, $class) !== 1) {
$class .= ucfirst($component);
}

Expand Down
28 changes: 13 additions & 15 deletions system/Commands/Generators/CellGenerator.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,7 +65,6 @@ class CellGenerator extends BaseCommand
*/
protected $options = [
'--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".',
'--suffix' => 'Append the component title to the class name (e.g. User => UserCell).',
'--force' => 'Force overwrite existing file.',
];

Expand All@@ -74,27 +73,26 @@ class CellGenerator extends BaseCommand
*/
public function run(array $params)
{
// Generate the Class first
$this->component = 'Cell';
$this->directory = 'Cells';
$this->component = 'Cell';
$this->directory = 'Cells';

$params = array_merge($params, ['suffix' => null]);

$this->template = 'cell.tpl.php';
$this->classNameLang = 'CLI.generator.className.cell';

$this->generateClass($params);

// Generate the View
$this->name = 'make:cell_view';
$this->template = 'cell_view.tpl.php';
$this->classNameLang = 'CLI.generator.viewName.cell';

// Form the view name
$segments = explode('\\', $this->qualifyClassName());

$view = array_pop($segments);
$view = decamelize($view);
$segments[] = $view;
$view = implode('\\', $segments);
$className = $this->qualifyClassName();
$viewName = decamelize(class_basename($className));
$viewName = preg_replace('/([a-z][a-z0-9_\/\\\\]+)(_cell)$/i', '$1', $viewName) ?? $viewName;
$namespace = substr($className, 0, strrpos($className, '\\') + 1);

$this->template = 'cell_view.tpl.php';
$this->generateView($namespace . $viewName, $params);

$this->generateView($view, $params);
return 0;
}
}
49 changes: 32 additions & 17 deletions system/View/Cells/Cell.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@
namespace CodeIgniter\View\Cells;

use CodeIgniter\Traits\PropertiesTrait;
use LogicException;
use ReflectionClass;

/**
Expand DownExpand Up@@ -64,37 +65,51 @@ public function setView(string $view)
* from within the view, this method extracts $data into the
* current scope and captures the output buffer instead of
* relying on the view service.
*
* @throws LogicException
*/
final protected function view(?string $view, array $data = []): string
{
$properties = $this->getPublicProperties();
$properties = $this->includeComputedProperties($properties);
$properties = array_merge($properties, $data);

// If no view is specified, we'll try to guess it based on the class name.
if (empty($view)) {
// According to the docs, the name of the view file should be the
// snake_cased version of the cell's class name, but for backward
// compatibility, the name also accepts '_cell' being omitted.
$ref = new ReflectionClass($this);
$view = decamelize($ref->getShortName());
$viewPath = dirname($ref->getFileName()) . DIRECTORY_SEPARATOR . $view . '.php';
$view = is_file($viewPath) ? $viewPath : str_replace('_cell', '', $view);
$view = (string) $view;

if ($view === '') {
$viewName = decamelize(class_basename(static::class));
$directory = dirname((new ReflectionClass($this))->getFileName()) . DIRECTORY_SEPARATOR;

$possibleView1 = $directory . substr($viewName, 0, strrpos($viewName, '_cell')) . '.php';
$possibleView2 = $directory . $viewName . '.php';
}

// Locate our view, preferring the directory of the class.
if (! is_file($view)) {
// Get the local pathname of the Cell
$ref = new ReflectionClass($this);
$view = dirname($ref->getFileName()) . DIRECTORY_SEPARATOR . $view . '.php';
if ($view !== '' && ! is_file($view)) {
$directory = dirname((new ReflectionClass($this))->getFileName()) . DIRECTORY_SEPARATOR;

$view = $directory . $view . '.php';
}

return (function () use ($properties, $view): string {
$candidateViews = array_filter(
[$view, $possibleView1 ?? '', $possibleView2 ?? ''],
static fn (string $path): bool => $path !== '' && is_file($path)
);

if ($candidateViews === []) {
throw new LogicException(sprintf(
'Cannot locate the view file for the "%s" cell.',
static::class
));
}

$foundView = current($candidateViews);

return (function () use ($properties, $foundView): string {
extract($properties);
ob_start();
include $view;
include $foundView;

return ob_get_clean() ?: '';
return ob_get_clean();
})();
}

Expand Down
18 changes: 18 additions & 0 deletions tests/_support/View/Cells/BadCell.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
<?php

/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace Tests\Support\View\Cells;

use CodeIgniter\View\Cells\Cell;

final class BadCell extends Cell
{
}
39 changes: 29 additions & 10 deletions tests/system/Commands/CellGeneratorTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -46,35 +46,54 @@ protected function getFileContents(string $filepath): string
return file_get_contents($filepath) ?: '';
}

public function testGenerateCell()
public function testGenerateCell(): void
{
command('make:cell RecentCell');

// Check the class was generated
$file = APPPATH . 'Cells/RecentCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$contents = $this->getFileContents($file);
$this->assertStringContainsString('class RecentCell extends Cell', $contents);
$this->assertStringContainsString('class RecentCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/recent_cell.php';
$this->assertStringContainsString('File created: ', $this->getStreamFilterBuffer());
$file = APPPATH . 'Cells/recent.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}

public function testGenerateCellSimpleName()
public function testGenerateCellSimpleName(): void
{
command('make:cell Another');

// Check the class was generated
$file = APPPATH . 'Cells/Another.php';
$file = APPPATH . 'Cells/AnotherCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$contents = $this->getFileContents($file);
$this->assertStringContainsString('class Another extends Cell', $contents);
$this->assertStringContainsString('class AnotherCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/another.php';
$this->assertStringContainsString('File created: ', $this->getStreamFilterBuffer());
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}

public function testGenerateCellWithCellInBetween(): void
{
command('make:cell PippoCellular');

// Check the class was generated
$file = APPPATH . 'Cells/PippoCellularCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertStringContainsString('class PippoCellularCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/pippo_cellular.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}
}
10 changes: 10 additions & 0 deletions tests/system/View/ControlledCellTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,8 +13,10 @@

use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\View\Exceptions\ViewException;
use LogicException;
use Tests\Support\View\Cells\AdditionCell;
use Tests\Support\View\Cells\AwesomeCell;
use Tests\Support\View\Cells\BadCell;
use Tests\Support\View\Cells\ColorsCell;
use Tests\Support\View\Cells\GreetingCell;
use Tests\Support\View\Cells\ListerCell;
Expand DownExpand Up@@ -65,6 +67,14 @@ public function testCellThroughRenderMethodWithExtraData()
$this->assertStringContainsString('42, 23, 16, 15, 8, 4', $result);
}

public function testCellThrowsExceptionWhenCannotFindTheViewFile()
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage('Cannot locate the view file for the "Tests\\Support\\View\\Cells\\BadCell" cell.');

view_cell(BadCell::class);
}

public function testCellWithParameters()
{
$result = view_cell(GreetingCell::class, 'greeting=Hi, name=CodeIgniter');
Expand Down
8 changes: 8 additions & 0 deletions user_guide_src/source/changelogs/v4.3.5.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,13 +18,21 @@ Message Changes
Changes
*******

- **make:cell** When creating a new cell, the controller would always have the ``Cell`` suffixed to the class name.
For the view file, the final ``_cell`` is always removed.
- **Cells** For compatibility with previous versions, view filenames ending with ``_cell`` can still be
located by the ``Cell`` as long as auto-detection of view file is enabled (via setting the ``$view`` property
to an empty string).

Deprecations
************

Bugs Fixed
**********

- **Validation:** Fixed a bug where a closure used in combination with ``permit_empty`` or ``if_exist`` rules was causing an error.
- **make:cell** Fixed generating view files as classes.
- **make:cell** Fixed treatment of single word class input for case-insensitive OS.

See the repo's
`CHANGELOG.md <https://github.com/codeigniter4/CodeIgniter4/blob/develop/CHANGELOG.md>`_
Expand Down
3 changes: 1 addition & 2 deletions user_guide_src/source/cli/cli_generators.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,12 +59,11 @@ Usage:

Argument:
=========
* ``name``: The name of the cell class. It should be in PascalCase.
* ``name``: The name of the cell class. It should be in PascalCase. **[REQUIRED]**

Options:
========
* ``--namespace``: Set the root namespace. Defaults to value of ``APP_NAMESPACE``.
* ``--suffix``: Append the component suffix to the generated class name.
* ``--force``: Set this flag to overwrite existing files on destination.

make:command
Expand Down
15 changes: 11 additions & 4 deletions user_guide_src/source/outgoing/view_cells.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -80,7 +80,14 @@ Controlled Cells

.. versionadded:: 4.3.0

Controlled Cells have two primary goals: to make it as fast as possible to build the cell, and provide additional logic and flexibility to your views, if they need it. The class must extend ``CodeIgniter\View\Cells\Cell``. They should have a view file in the same folder. By convention the class name should be PascalCase and the view should be the snake_cased version of the class name. So, for example, if you have a ``MyCell`` class, the view file should be ``my_cell.php``.
Controlled cells have two primary goals: to make it as fast as possible to build the cell, and provide additional logic and
flexibility to your views, if they need it. The class must extend ``CodeIgniter\View\Cells\Cell``. They should have a view file
in the same folder. By convention, the class name should be in PascalCase suffixed with ``Cell`` and the view should be
the snake_cased version of the class name, without the suffix. For example, if you have a ``MyCell`` class, the view file
should be ``my.php``.

.. note:: Prior to v4.3.5, the generated view file ends with ``_cell.php``. Though v4.3.5 and newer will generate view files
without the ``_cell`` suffix, existing view files will still be located and loaded.

Creating a Controlled Cell
==========================
Expand All@@ -99,7 +106,7 @@ At the most basic level, all you need to implement within the class are public p
public $message;
}

// app/Cells/alert_message_cell.php
// app/Cells/alert_message.php
<div class="alert alert-<?= esc($type, 'attr') ?>">
<?= esc($message) ?>
</div>
Expand DownExpand Up@@ -199,7 +206,7 @@ If you need to perform additional logic for one or more properties you can use c
}
}

// app/Cells/alert_message_cell.php
// app/Cells/alert_message.php
<div>
<p>type - <?= esc($type) ?></p>
<p>message - <?= esc($message) ?></p>
Expand DownExpand Up@@ -230,7 +237,7 @@ Sometimes you need to perform additional logic for the view, but you don't want
}
}

// app/Cells/recent_posts_cell.php
// app/Cells/recent_posts.php
<ul>
<?php foreach ($posts as $post): ?>
<li><?= $this->linkPost($post) ?></li>
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/Config/Generators.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,7 @@ class Generators extends BaseConfig
*/
public array $views = [
'make:cell' => 'CodeIgniter\Commands\Generators\Views\cell.tpl.php',
'make:cell_view' => 'CodeIgniter\Commands\Generators\Views\cell_view.tpl.php',
'make:command' => 'CodeIgniter\Commands\Generators\Views\command.tpl.php',
'make:config' => 'CodeIgniter\Commands\Generators\Views\config.tpl.php',
'make:controller' => 'CodeIgniter\Commands\Generators\Views\controller.tpl.php',
Expand Down
6 changes: 3 additions & 3 deletions system/CLI/GeneratorTrait.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -235,15 +235,15 @@ protected function qualifyClassName(): string
$component = singular($this->component);

/**
* @see https://regex101.com/r/a5KNCR/1
* @see https://regex101.com/r/a5KNCR/2
*/
$pattern = sprintf('/([a-z][a-z0-9_\/\\\\]+)(%s)/i', $component);
$pattern = sprintf('/([a-z][a-z0-9_\/\\\\]+)(%s)$/i', $component);

if (preg_match($pattern, $class, $matches) === 1) {
$class = $matches[1] . ucfirst($matches[2]);
}

if ($this->enabledSuffixing && $this->getOption('suffix') && ! strripos($class, $component)) {
if ($this->enabledSuffixing && $this->getOption('suffix') && preg_match($pattern, $class) !== 1) {
$class .= ucfirst($component);
}

Expand Down
28 changes: 13 additions & 15 deletions system/Commands/Generators/CellGenerator.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,7 +65,6 @@ class CellGenerator extends BaseCommand
*/
protected $options = [
'--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".',
'--suffix' => 'Append the component title to the class name (e.g. User => UserCell).',
'--force' => 'Force overwrite existing file.',
];

Expand All@@ -74,27 +73,26 @@ class CellGenerator extends BaseCommand
*/
public function run(array $params)
{
// Generate the Class first
$this->component = 'Cell';
$this->directory = 'Cells';
$this->component = 'Cell';
$this->directory = 'Cells';

$params = array_merge($params, ['suffix' => null]);

$this->template = 'cell.tpl.php';
$this->classNameLang = 'CLI.generator.className.cell';

$this->generateClass($params);

// Generate the View
$this->name = 'make:cell_view';
$this->template = 'cell_view.tpl.php';
$this->classNameLang = 'CLI.generator.viewName.cell';

// Form the view name
$segments = explode('\\', $this->qualifyClassName());

$view = array_pop($segments);
$view = decamelize($view);
$segments[] = $view;
$view = implode('\\', $segments);
$className = $this->qualifyClassName();
$viewName = decamelize(class_basename($className));
$viewName = preg_replace('/([a-z][a-z0-9_\/\\\\]+)(_cell)$/i', '$1', $viewName) ?? $viewName;
$namespace = substr($className, 0, strrpos($className, '\\') + 1);

$this->template = 'cell_view.tpl.php';
$this->generateView($namespace . $viewName, $params);

$this->generateView($view, $params);
return 0;
}
}
49 changes: 32 additions & 17 deletions system/View/Cells/Cell.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@
namespace CodeIgniter\View\Cells;

use CodeIgniter\Traits\PropertiesTrait;
use LogicException;
use ReflectionClass;

/**
Expand DownExpand Up@@ -64,37 +65,51 @@ public function setView(string $view)
* from within the view, this method extracts $data into the
* current scope and captures the output buffer instead of
* relying on the view service.
*
* @throws LogicException
*/
final protected function view(?string $view, array $data = []): string
{
$properties = $this->getPublicProperties();
$properties = $this->includeComputedProperties($properties);
$properties = array_merge($properties, $data);

// If no view is specified, we'll try to guess it based on the class name.
if (empty($view)) {
// According to the docs, the name of the view file should be the
// snake_cased version of the cell's class name, but for backward
// compatibility, the name also accepts '_cell' being omitted.
$ref = new ReflectionClass($this);
$view = decamelize($ref->getShortName());
$viewPath = dirname($ref->getFileName()) . DIRECTORY_SEPARATOR . $view . '.php';
$view = is_file($viewPath) ? $viewPath : str_replace('_cell', '', $view);
$view = (string) $view;

if ($view === '') {
$viewName = decamelize(class_basename(static::class));
$directory = dirname((new ReflectionClass($this))->getFileName()) . DIRECTORY_SEPARATOR;

$possibleView1 = $directory . substr($viewName, 0, strrpos($viewName, '_cell')) . '.php';
$possibleView2 = $directory . $viewName . '.php';
}

// Locate our view, preferring the directory of the class.
if (! is_file($view)) {
// Get the local pathname of the Cell
$ref = new ReflectionClass($this);
$view = dirname($ref->getFileName()) . DIRECTORY_SEPARATOR . $view . '.php';
if ($view !== '' && ! is_file($view)) {
$directory = dirname((new ReflectionClass($this))->getFileName()) . DIRECTORY_SEPARATOR;

$view = $directory . $view . '.php';
}

return (function () use ($properties, $view): string {
$candidateViews = array_filter(
[$view, $possibleView1 ?? '', $possibleView2 ?? ''],
static fn (string $path): bool => $path !== '' && is_file($path)
);

if ($candidateViews === []) {
throw new LogicException(sprintf(
'Cannot locate the view file for the "%s" cell.',
static::class
));
}

$foundView = current($candidateViews);

return (function () use ($properties, $foundView): string {
extract($properties);
ob_start();
include $view;
include $foundView;

return ob_get_clean() ?: '';
return ob_get_clean();
})();
}

Expand Down
18 changes: 18 additions & 0 deletions tests/_support/View/Cells/BadCell.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
<?php

/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace Tests\Support\View\Cells;

use CodeIgniter\View\Cells\Cell;

final class BadCell extends Cell
{
}
39 changes: 29 additions & 10 deletions tests/system/Commands/CellGeneratorTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -46,35 +46,54 @@ protected function getFileContents(string $filepath): string
return file_get_contents($filepath) ?: '';
}

public function testGenerateCell()
public function testGenerateCell(): void
{
command('make:cell RecentCell');

// Check the class was generated
$file = APPPATH . 'Cells/RecentCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$contents = $this->getFileContents($file);
$this->assertStringContainsString('class RecentCell extends Cell', $contents);
$this->assertStringContainsString('class RecentCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/recent_cell.php';
$this->assertStringContainsString('File created: ', $this->getStreamFilterBuffer());
$file = APPPATH . 'Cells/recent.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}

public function testGenerateCellSimpleName()
public function testGenerateCellSimpleName(): void
{
command('make:cell Another');

// Check the class was generated
$file = APPPATH . 'Cells/Another.php';
$file = APPPATH . 'Cells/AnotherCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$contents = $this->getFileContents($file);
$this->assertStringContainsString('class Another extends Cell', $contents);
$this->assertStringContainsString('class AnotherCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/another.php';
$this->assertStringContainsString('File created: ', $this->getStreamFilterBuffer());
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}

public function testGenerateCellWithCellInBetween(): void
{
command('make:cell PippoCellular');

// Check the class was generated
$file = APPPATH . 'Cells/PippoCellularCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertStringContainsString('class PippoCellularCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/pippo_cellular.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}
}
10 changes: 10 additions & 0 deletions tests/system/View/ControlledCellTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,8 +13,10 @@

use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\View\Exceptions\ViewException;
use LogicException;
use Tests\Support\View\Cells\AdditionCell;
use Tests\Support\View\Cells\AwesomeCell;
use Tests\Support\View\Cells\BadCell;
use Tests\Support\View\Cells\ColorsCell;
use Tests\Support\View\Cells\GreetingCell;
use Tests\Support\View\Cells\ListerCell;
Expand DownExpand Up@@ -65,6 +67,14 @@ public function testCellThroughRenderMethodWithExtraData()
$this->assertStringContainsString('42, 23, 16, 15, 8, 4', $result);
}

public function testCellThrowsExceptionWhenCannotFindTheViewFile()
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage('Cannot locate the view file for the "Tests\\Support\\View\\Cells\\BadCell" cell.');

view_cell(BadCell::class);
}

public function testCellWithParameters()
{
$result = view_cell(GreetingCell::class, 'greeting=Hi, name=CodeIgniter');
Expand Down
8 changes: 8 additions & 0 deletions user_guide_src/source/changelogs/v4.3.5.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,13 +18,21 @@ Message Changes
Changes
*******

- **make:cell** When creating a new cell, the controller would always have the ``Cell`` suffixed to the class name.
For the view file, the final ``_cell`` is always removed.
- **Cells** For compatibility with previous versions, view filenames ending with ``_cell`` can still be
located by the ``Cell`` as long as auto-detection of view file is enabled (via setting the ``$view`` property
to an empty string).

Deprecations
************

Bugs Fixed
**********

- **Validation:** Fixed a bug where a closure used in combination with ``permit_empty`` or ``if_exist`` rules was causing an error.
- **make:cell** Fixed generating view files as classes.
- **make:cell** Fixed treatment of single word class input for case-insensitive OS.

See the repo's
`CHANGELOG.md <https://github.com/codeigniter4/CodeIgniter4/blob/develop/CHANGELOG.md>`_
Expand Down
3 changes: 1 addition & 2 deletions user_guide_src/source/cli/cli_generators.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,12 +59,11 @@ Usage:

Argument:
=========
* ``name``: The name of the cell class. It should be in PascalCase.
* ``name``: The name of the cell class. It should be in PascalCase. **[REQUIRED]**

Options:
========
* ``--namespace``: Set the root namespace. Defaults to value of ``APP_NAMESPACE``.
* ``--suffix``: Append the component suffix to the generated class name.
* ``--force``: Set this flag to overwrite existing files on destination.

make:command
Expand Down
15 changes: 11 additions & 4 deletions user_guide_src/source/outgoing/view_cells.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -80,7 +80,14 @@ Controlled Cells

.. versionadded:: 4.3.0

Controlled Cells have two primary goals: to make it as fast as possible to build the cell, and provide additional logic and flexibility to your views, if they need it. The class must extend ``CodeIgniter\View\Cells\Cell``. They should have a view file in the same folder. By convention the class name should be PascalCase and the view should be the snake_cased version of the class name. So, for example, if you have a ``MyCell`` class, the view file should be ``my_cell.php``.
Controlled cells have two primary goals: to make it as fast as possible to build the cell, and provide additional logic and
flexibility to your views, if they need it. The class must extend ``CodeIgniter\View\Cells\Cell``. They should have a view file
in the same folder. By convention, the class name should be in PascalCase suffixed with ``Cell`` and the view should be
the snake_cased version of the class name, without the suffix. For example, if you have a ``MyCell`` class, the view file
should be ``my.php``.

.. note:: Prior to v4.3.5, the generated view file ends with ``_cell.php``. Though v4.3.5 and newer will generate view files
without the ``_cell`` suffix, existing view files will still be located and loaded.

Creating a Controlled Cell
==========================
Expand All@@ -99,7 +106,7 @@ At the most basic level, all you need to implement within the class are public p
public $message;
}

// app/Cells/alert_message_cell.php
// app/Cells/alert_message.php
<div class="alert alert-<?= esc($type, 'attr') ?>">
<?= esc($message) ?>
</div>
Expand DownExpand Up@@ -199,7 +206,7 @@ If you need to perform additional logic for one or more properties you can use c
}
}

// app/Cells/alert_message_cell.php
// app/Cells/alert_message.php
<div>
<p>type - <?= esc($type) ?></p>
<p>message - <?= esc($message) ?></p>
Expand DownExpand Up@@ -230,7 +237,7 @@ Sometimes you need to perform additional logic for the view, but you don't want
}
}

// app/Cells/recent_posts_cell.php
// app/Cells/recent_posts.php
<ul>
<?php foreach ($posts as $post): ?>
<li><?= $this->linkPost($post) ?></li>
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/Config/Generators.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,7 @@ class Generators extends BaseConfig
*/
public array $views = [
'make:cell' => 'CodeIgniter\Commands\Generators\Views\cell.tpl.php',
'make:cell_view' => 'CodeIgniter\Commands\Generators\Views\cell_view.tpl.php',
'make:command' => 'CodeIgniter\Commands\Generators\Views\command.tpl.php',
'make:config' => 'CodeIgniter\Commands\Generators\Views\config.tpl.php',
'make:controller' => 'CodeIgniter\Commands\Generators\Views\controller.tpl.php',
Expand Down
6 changes: 3 additions & 3 deletions system/CLI/GeneratorTrait.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -235,15 +235,15 @@ protected function qualifyClassName(): string
$component = singular($this->component);

/**
* @see https://regex101.com/r/a5KNCR/1
* @see https://regex101.com/r/a5KNCR/2
*/
$pattern = sprintf('/([a-z][a-z0-9_\/\\\\]+)(%s)/i', $component);
$pattern = sprintf('/([a-z][a-z0-9_\/\\\\]+)(%s)$/i', $component);

if (preg_match($pattern, $class, $matches) === 1) {
$class = $matches[1] . ucfirst($matches[2]);
}

if ($this->enabledSuffixing && $this->getOption('suffix') && ! strripos($class, $component)) {
if ($this->enabledSuffixing && $this->getOption('suffix') && preg_match($pattern, $class) !== 1) {
$class .= ucfirst($component);
}

Expand Down
28 changes: 13 additions & 15 deletions system/Commands/Generators/CellGenerator.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,7 +65,6 @@ class CellGenerator extends BaseCommand
*/
protected $options = [
'--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".',
'--suffix' => 'Append the component title to the class name (e.g. User => UserCell).',
'--force' => 'Force overwrite existing file.',
];

Expand All@@ -74,27 +73,26 @@ class CellGenerator extends BaseCommand
*/
public function run(array $params)
{
// Generate the Class first
$this->component = 'Cell';
$this->directory = 'Cells';
$this->component = 'Cell';
$this->directory = 'Cells';

$params = array_merge($params, ['suffix' => null]);

$this->template = 'cell.tpl.php';
$this->classNameLang = 'CLI.generator.className.cell';

$this->generateClass($params);

// Generate the View
$this->name = 'make:cell_view';
$this->template = 'cell_view.tpl.php';
$this->classNameLang = 'CLI.generator.viewName.cell';

// Form the view name
$segments = explode('\\', $this->qualifyClassName());

$view = array_pop($segments);
$view = decamelize($view);
$segments[] = $view;
$view = implode('\\', $segments);
$className = $this->qualifyClassName();
$viewName = decamelize(class_basename($className));
$viewName = preg_replace('/([a-z][a-z0-9_\/\\\\]+)(_cell)$/i', '$1', $viewName) ?? $viewName;
$namespace = substr($className, 0, strrpos($className, '\\') + 1);

$this->template = 'cell_view.tpl.php';
$this->generateView($namespace . $viewName, $params);

$this->generateView($view, $params);
return 0;
}
}
49 changes: 32 additions & 17 deletions system/View/Cells/Cell.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@
namespace CodeIgniter\View\Cells;

use CodeIgniter\Traits\PropertiesTrait;
use LogicException;
use ReflectionClass;

/**
Expand DownExpand Up@@ -64,37 +65,51 @@ public function setView(string $view)
* from within the view, this method extracts $data into the
* current scope and captures the output buffer instead of
* relying on the view service.
*
* @throws LogicException
*/
final protected function view(?string $view, array $data = []): string
{
$properties = $this->getPublicProperties();
$properties = $this->includeComputedProperties($properties);
$properties = array_merge($properties, $data);

// If no view is specified, we'll try to guess it based on the class name.
if (empty($view)) {
// According to the docs, the name of the view file should be the
// snake_cased version of the cell's class name, but for backward
// compatibility, the name also accepts '_cell' being omitted.
$ref = new ReflectionClass($this);
$view = decamelize($ref->getShortName());
$viewPath = dirname($ref->getFileName()) . DIRECTORY_SEPARATOR . $view . '.php';
$view = is_file($viewPath) ? $viewPath : str_replace('_cell', '', $view);
$view = (string) $view;

if ($view === '') {
$viewName = decamelize(class_basename(static::class));
$directory = dirname((new ReflectionClass($this))->getFileName()) . DIRECTORY_SEPARATOR;

$possibleView1 = $directory . substr($viewName, 0, strrpos($viewName, '_cell')) . '.php';
$possibleView2 = $directory . $viewName . '.php';
}

// Locate our view, preferring the directory of the class.
if (! is_file($view)) {
// Get the local pathname of the Cell
$ref = new ReflectionClass($this);
$view = dirname($ref->getFileName()) . DIRECTORY_SEPARATOR . $view . '.php';
if ($view !== '' && ! is_file($view)) {
$directory = dirname((new ReflectionClass($this))->getFileName()) . DIRECTORY_SEPARATOR;

$view = $directory . $view . '.php';
}

return (function () use ($properties, $view): string {
$candidateViews = array_filter(
[$view, $possibleView1 ?? '', $possibleView2 ?? ''],
static fn (string $path): bool => $path !== '' && is_file($path)
);

if ($candidateViews === []) {
throw new LogicException(sprintf(
'Cannot locate the view file for the "%s" cell.',
static::class
));
}

$foundView = current($candidateViews);

return (function () use ($properties, $foundView): string {
extract($properties);
ob_start();
include $view;
include $foundView;

return ob_get_clean() ?: '';
return ob_get_clean();
})();
}

Expand Down
18 changes: 18 additions & 0 deletions tests/_support/View/Cells/BadCell.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
<?php

/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace Tests\Support\View\Cells;

use CodeIgniter\View\Cells\Cell;

final class BadCell extends Cell
{
}
39 changes: 29 additions & 10 deletions tests/system/Commands/CellGeneratorTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -46,35 +46,54 @@ protected function getFileContents(string $filepath): string
return file_get_contents($filepath) ?: '';
}

public function testGenerateCell()
public function testGenerateCell(): void
{
command('make:cell RecentCell');

// Check the class was generated
$file = APPPATH . 'Cells/RecentCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$contents = $this->getFileContents($file);
$this->assertStringContainsString('class RecentCell extends Cell', $contents);
$this->assertStringContainsString('class RecentCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/recent_cell.php';
$this->assertStringContainsString('File created: ', $this->getStreamFilterBuffer());
$file = APPPATH . 'Cells/recent.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}

public function testGenerateCellSimpleName()
public function testGenerateCellSimpleName(): void
{
command('make:cell Another');

// Check the class was generated
$file = APPPATH . 'Cells/Another.php';
$file = APPPATH . 'Cells/AnotherCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$contents = $this->getFileContents($file);
$this->assertStringContainsString('class Another extends Cell', $contents);
$this->assertStringContainsString('class AnotherCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/another.php';
$this->assertStringContainsString('File created: ', $this->getStreamFilterBuffer());
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}

public function testGenerateCellWithCellInBetween(): void
{
command('make:cell PippoCellular');

// Check the class was generated
$file = APPPATH . 'Cells/PippoCellularCell.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertStringContainsString('class PippoCellularCell extends Cell', $this->getFileContents($file));

// Check the view was generated
$file = APPPATH . 'Cells/pippo_cellular.php';
$this->assertStringContainsString('File created: ' . clean_path($file), $this->getStreamFilterBuffer());
$this->assertFileExists($file);
$this->assertSame("<div>\n <!-- Your HTML here -->\n</div>\n", $this->getFileContents($file));
}
}
10 changes: 10 additions & 0 deletions tests/system/View/ControlledCellTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,8 +13,10 @@

use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\View\Exceptions\ViewException;
use LogicException;
use Tests\Support\View\Cells\AdditionCell;
use Tests\Support\View\Cells\AwesomeCell;
use Tests\Support\View\Cells\BadCell;
use Tests\Support\View\Cells\ColorsCell;
use Tests\Support\View\Cells\GreetingCell;
use Tests\Support\View\Cells\ListerCell;
Expand DownExpand Up@@ -65,6 +67,14 @@ public function testCellThroughRenderMethodWithExtraData()
$this->assertStringContainsString('42, 23, 16, 15, 8, 4', $result);
}

public function testCellThrowsExceptionWhenCannotFindTheViewFile()
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage('Cannot locate the view file for the "Tests\\Support\\View\\Cells\\BadCell" cell.');

view_cell(BadCell::class);
}

public function testCellWithParameters()
{
$result = view_cell(GreetingCell::class, 'greeting=Hi, name=CodeIgniter');
Expand Down
8 changes: 8 additions & 0 deletions user_guide_src/source/changelogs/v4.3.5.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,13 +18,21 @@ Message Changes
Changes
*******

- **make:cell** When creating a new cell, the controller would always have the ``Cell`` suffixed to the class name.
For the view file, the final ``_cell`` is always removed.
- **Cells** For compatibility with previous versions, view filenames ending with ``_cell`` can still be
located by the ``Cell`` as long as auto-detection of view file is enabled (via setting the ``$view`` property
to an empty string).

Deprecations
************

Bugs Fixed
**********

- **Validation:** Fixed a bug where a closure used in combination with ``permit_empty`` or ``if_exist`` rules was causing an error.
- **make:cell** Fixed generating view files as classes.
- **make:cell** Fixed treatment of single word class input for case-insensitive OS.

See the repo's
`CHANGELOG.md <https://github.com/codeigniter4/CodeIgniter4/blob/develop/CHANGELOG.md>`_
Expand Down
3 changes: 1 addition & 2 deletions user_guide_src/source/cli/cli_generators.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,12 +59,11 @@ Usage:

Argument:
=========
* ``name``: The name of the cell class. It should be in PascalCase.
* ``name``: The name of the cell class. It should be in PascalCase. **[REQUIRED]**

Options:
========
* ``--namespace``: Set the root namespace. Defaults to value of ``APP_NAMESPACE``.
* ``--suffix``: Append the component suffix to the generated class name.
* ``--force``: Set this flag to overwrite existing files on destination.

make:command
Expand Down
15 changes: 11 additions & 4 deletions user_guide_src/source/outgoing/view_cells.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -80,7 +80,14 @@ Controlled Cells

.. versionadded:: 4.3.0

Controlled Cells have two primary goals: to make it as fast as possible to build the cell, and provide additional logic and flexibility to your views, if they need it. The class must extend ``CodeIgniter\View\Cells\Cell``. They should have a view file in the same folder. By convention the class name should be PascalCase and the view should be the snake_cased version of the class name. So, for example, if you have a ``MyCell`` class, the view file should be ``my_cell.php``.
Controlled cells have two primary goals: to make it as fast as possible to build the cell, and provide additional logic and
flexibility to your views, if they need it. The class must extend ``CodeIgniter\View\Cells\Cell``. They should have a view file
in the same folder. By convention, the class name should be in PascalCase suffixed with ``Cell`` and the view should be
the snake_cased version of the class name, without the suffix. For example, if you have a ``MyCell`` class, the view file
should be ``my.php``.

.. note:: Prior to v4.3.5, the generated view file ends with ``_cell.php``. Though v4.3.5 and newer will generate view files
without the ``_cell`` suffix, existing view files will still be located and loaded.

Creating a Controlled Cell
==========================
Expand All@@ -99,7 +106,7 @@ At the most basic level, all you need to implement within the class are public p
public $message;
}

// app/Cells/alert_message_cell.php
// app/Cells/alert_message.php
<div class="alert alert-<?= esc($type, 'attr') ?>">
<?= esc($message) ?>
</div>
Expand DownExpand Up@@ -199,7 +206,7 @@ If you need to perform additional logic for one or more properties you can use c
}
}

// app/Cells/alert_message_cell.php
// app/Cells/alert_message.php
<div>
<p>type - <?= esc($type) ?></p>
<p>message - <?= esc($message) ?></p>
Expand DownExpand Up@@ -230,7 +237,7 @@ Sometimes you need to perform additional logic for the view, but you don't want
}
}

// app/Cells/recent_posts_cell.php
// app/Cells/recent_posts.php
<ul>
<?php foreach ($posts as $post): ?>
<li><?= $this->linkPost($post) ?></li>
Expand Down