Browse Source

Remove engine config from NumberHelper and TextHelper

Corey Taylor 4 years ago
parent
commit
2b832837df

+ 8 - 109
src/View/Helper/NumberHelper.php

@@ -16,66 +16,24 @@ declare(strict_types=1);
  */
 namespace Cake\View\Helper;
 
-use Cake\Core\App;
-use Cake\Core\Exception\CakeException;
 use Cake\I18n\Number;
 use Cake\View\Helper;
-use Cake\View\View;
 
 /**
  * Number helper library.
  *
  * Methods to make numbers more readable.
  *
+ * @method string ordinal(float|int $value, array $options = []) See Number::ordinal()
+ * @method string precision(string|float|int $number, int $precision = 3, array $options = []) See Number::precision()
+ * @method string toPercentage(string|float|int $value, int $precision = 3, array $options = []) See Number::toPercentage()
+ * @method string toReadableSize(string|float|int $size) See Number::toReadableSize()
  * @link https://book.cakephp.org/4/en/views/helpers/number.html
  * @see \Cake\I18n\Number
  */
 class NumberHelper extends Helper
 {
     /**
-     * Default config for this class
-     *
-     * @var array<string, mixed>
-     */
-    protected array $_defaultConfig = [
-        'engine' => Number::class,
-    ];
-
-    /**
-     * Cake\I18n\Number instance
-     *
-     * @var \Cake\I18n\Number
-     */
-    protected $_engine;
-
-    /**
-     * Default Constructor
-     *
-     * ### Settings:
-     *
-     * - `engine` Class name to use to replace Cake\I18n\Number functionality
-     *            The class needs to be placed in the `Utility` directory.
-     *
-     * @param \Cake\View\View $view The View this helper is being attached to.
-     * @param array<string, mixed> $config Configuration settings for the helper
-     * @throws \Cake\Core\Exception\CakeException When the engine class could not be found.
-     */
-    public function __construct(View $view, array $config = [])
-    {
-        parent::__construct($view, $config);
-
-        $config = $this->_config;
-
-        /** @psalm-var class-string<\Cake\I18n\Number>|null $engineClass */
-        $engineClass = App::className($config['engine'], 'Utility');
-        if ($engineClass === null) {
-            throw new CakeException(sprintf('Class for %s could not be found', $config['engine']));
-        }
-
-        $this->_engine = new $engineClass($config);
-    }
-
-    /**
      * Call methods from Cake\I18n\Number utility class
      *
      * @param string $method Method to invoke
@@ -84,54 +42,7 @@ class NumberHelper extends Helper
      */
     public function __call(string $method, array $params): mixed
     {
-        return $this->_engine->{$method}(...$params);
-    }
-
-    /**
-     * Formats a number with a level of precision.
-     *
-     * @param string|float $number A floating point number.
-     * @param int $precision The precision of the returned number.
-     * @param array<string, mixed> $options Additional options.
-     * @return string Formatted float.
-     * @see \Cake\I18n\Number::precision()
-     * @link https://book.cakephp.org/4/en/views/helpers/number.html#formatting-floating-point-numbers
-     */
-    public function precision(string|float $number, int $precision = 3, array $options = []): string
-    {
-        return $this->_engine->precision($number, $precision, $options);
-    }
-
-    /**
-     * Returns a formatted-for-humans file size.
-     *
-     * @param string|float|int $size Size in bytes
-     * @return string Human readable size
-     * @see \Cake\I18n\Number::toReadableSize()
-     * @link https://book.cakephp.org/4/en/views/helpers/number.html#interacting-with-human-readable-values
-     */
-    public function toReadableSize(string|float|int $size): string
-    {
-        return $this->_engine->toReadableSize($size);
-    }
-
-    /**
-     * Formats a number into a percentage string.
-     *
-     * Options:
-     *
-     * - `multiply`: Multiply the input value by 100 for decimal percentages.
-     *
-     * @param string|float $number A floating point number
-     * @param int $precision The precision of the returned number
-     * @param array<string, mixed> $options Options
-     * @return string Percentage string
-     * @see \Cake\I18n\Number::toPercentage()
-     * @link https://book.cakephp.org/4/en/views/helpers/number.html#formatting-percentages
-     */
-    public function toPercentage(string|float $number, int $precision = 2, array $options = []): string
-    {
-        return $this->_engine->toPercentage($number, $precision, $options);
+        return Number::{$method}(...$params);
     }
 
     /**
@@ -153,7 +64,7 @@ class NumberHelper extends Helper
      */
     public function format(string|float $number, array $options = []): string
     {
-        $formatted = $this->_engine->format($number, $options);
+        $formatted = Number::format($number, $options);
         $options += ['escape' => true];
 
         return $options['escape'] ? h($formatted) : $formatted;
@@ -185,7 +96,7 @@ class NumberHelper extends Helper
      */
     public function currency(string|float $number, ?string $currency = null, array $options = []): string
     {
-        $formatted = $this->_engine->currency($number, $currency, $options);
+        $formatted = Number::currency($number, $currency, $options);
         $options += ['escape' => true];
 
         return $options['escape'] ? h($formatted) : $formatted;
@@ -209,7 +120,7 @@ class NumberHelper extends Helper
      */
     public function formatDelta(string|float $value, array $options = []): string
     {
-        $formatted = $this->_engine->formatDelta($value, $options);
+        $formatted = Number::formatDelta($value, $options);
         $options += ['escape' => true];
 
         return $options['escape'] ? h($formatted) : $formatted;
@@ -224,16 +135,4 @@ class NumberHelper extends Helper
     {
         return [];
     }
-
-    /**
-     * Formats a number into locale specific ordinal suffix.
-     *
-     * @param float|int $value An integer
-     * @param array<string, mixed> $options An array with options.
-     * @return string formatted number
-     */
-    public function ordinal(float|int $value, array $options = []): string
-    {
-        return $this->_engine->ordinal($value, $options);
-    }
 }

+ 7 - 168
src/View/Helper/TextHelper.php

@@ -16,12 +16,9 @@ declare(strict_types=1);
  */
 namespace Cake\View\Helper;
 
-use Cake\Core\App;
-use Cake\Core\Exception\CakeException;
 use Cake\Utility\Security;
 use Cake\Utility\Text;
 use Cake\View\Helper;
-use Cake\View\View;
 
 /**
  * Text helper library.
@@ -29,6 +26,12 @@ use Cake\View\View;
  * Text manipulations: Highlight, excerpt, truncate, strip of links, convert email addresses to mailto: links...
  *
  * @property \Cake\View\Helper\HtmlHelper $Html
+ * @method string excerpt(string $text, string $phrase, int $radius = 100, string $ending = '...') See Text::excerpt()
+ * @method string highlight(string $text, array|string $phrase, array $options = []) See Text::highlight()
+ * @method string slug(string $string, array|string $options = []) See Text::slug()
+ * @method string tail(string $text, int $length = 100, array $options = []) See Text::tail()
+ * @method string toList(array $list, ?string $and = null, string $separator = ', ') See Text::toList()
+ * @method string truncate(string $text, int $length = 100, array $options = []) See Text::truncate()
  * @link https://book.cakephp.org/4/en/views/helpers/text.html
  * @see \Cake\Utility\Text
  */
@@ -42,15 +45,6 @@ class TextHelper extends Helper
     protected array $helpers = ['Html'];
 
     /**
-     * Default config for this class
-     *
-     * @var array<string, mixed>
-     */
-    protected array $_defaultConfig = [
-        'engine' => Text::class,
-    ];
-
-    /**
      * An array of hashes and their contents.
      * Used when inserting links into text.
      *
@@ -59,40 +53,6 @@ class TextHelper extends Helper
     protected array $_placeholders = [];
 
     /**
-     * Cake Utility Text instance
-     *
-     * @var \Cake\Utility\Text
-     */
-    protected $_engine;
-
-    /**
-     * Constructor
-     *
-     * ### Settings:
-     *
-     * - `engine` Class name to use to replace String functionality.
-     *            The class needs to be placed in the `Utility` directory.
-     *
-     * @param \Cake\View\View $view the view object the helper is attached to.
-     * @param array<string, mixed> $config Settings array Settings array
-     * @throws \Cake\Core\Exception\CakeException when the engine class could not be found.
-     */
-    public function __construct(View $view, array $config = [])
-    {
-        parent::__construct($view, $config);
-
-        $config = $this->_config;
-
-        /** @psalm-var class-string<\Cake\Utility\Text>|null $engineClass */
-        $engineClass = App::className($config['engine'], 'Utility');
-        if ($engineClass === null) {
-            throw new CakeException(sprintf('Class for %s could not be found', $config['engine']));
-        }
-
-        $this->_engine = new $engineClass($config);
-    }
-
-    /**
      * Call methods from String utility class
      *
      * @param string $method Method to invoke
@@ -101,7 +61,7 @@ class TextHelper extends Helper
      */
     public function __call(string $method, array $params): mixed
     {
-        return $this->_engine->{$method}(...$params);
+        return Text::{$method}(...$params);
     }
 
     /**
@@ -277,22 +237,6 @@ class TextHelper extends Helper
     }
 
     /**
-     * Highlights a given phrase in a text. You can specify any expression in highlighter that
-     * may include the \1 expression to include the $phrase found.
-     *
-     * @param string $text Text to search the phrase in
-     * @param string $phrase The phrase that will be searched
-     * @param array<string, mixed> $options An array of HTML attributes and options.
-     * @return string The highlighted text
-     * @see \Cake\Utility\Text::highlight()
-     * @link https://book.cakephp.org/4/en/views/helpers/text.html#highlighting-substrings
-     */
-    public function highlight(string $text, string $phrase, array $options = []): string
-    {
-        return $this->_engine->highlight($text, $phrase, $options);
-    }
-
-    /**
      * Formats paragraphs around given text for all line breaks
      *  <br /> added for single line return
      *  <p> added for double line return
@@ -319,111 +263,6 @@ class TextHelper extends Helper
     }
 
     /**
-     * Truncates text.
-     *
-     * Cuts a string to the length of $length and replaces the last characters
-     * with the ellipsis if the text is longer than length.
-     *
-     * ### Options:
-     *
-     * - `ellipsis` Will be used as Ending and appended to the trimmed string
-     * - `exact` If false, $text will not be cut mid-word
-     * - `html` If true, HTML tags would be handled correctly
-     *
-     * @param string $text String to truncate.
-     * @param int $length Length of returned string, including ellipsis.
-     * @param array<string, mixed> $options An array of HTML attributes and options.
-     * @return string Trimmed string.
-     * @see \Cake\Utility\Text::truncate()
-     * @link https://book.cakephp.org/4/en/views/helpers/text.html#truncating-text
-     */
-    public function truncate(string $text, int $length = 100, array $options = []): string
-    {
-        return $this->_engine->truncate($text, $length, $options);
-    }
-
-    /**
-     * Truncates text starting from the end.
-     *
-     * Cuts a string to the length of $length and replaces the first characters
-     * with the ellipsis if the text is longer than length.
-     *
-     * ### Options:
-     *
-     * - `ellipsis` Will be used as Beginning and prepended to the trimmed string
-     * - `exact` If false, $text will not be cut mid-word
-     *
-     * @param string $text String to truncate.
-     * @param int $length Length of returned string, including ellipsis.
-     * @param array<string, mixed> $options An array of HTML attributes and options.
-     * @return string Trimmed string.
-     * @see \Cake\Utility\Text::tail()
-     * @link https://book.cakephp.org/4/en/views/helpers/text.html#truncating-the-tail-of-a-string
-     */
-    public function tail(string $text, int $length = 100, array $options = []): string
-    {
-        return $this->_engine->tail($text, $length, $options);
-    }
-
-    /**
-     * Extracts an excerpt from the text surrounding the phrase with a number of characters on each side
-     * determined by radius.
-     *
-     * @param string $text String to search the phrase in
-     * @param string $phrase Phrase that will be searched for
-     * @param int $radius The amount of characters that will be returned on each side of the founded phrase
-     * @param string $ending Ending that will be appended
-     * @return string Modified string
-     * @see \Cake\Utility\Text::excerpt()
-     * @link https://book.cakephp.org/4/en/views/helpers/text.html#extracting-an-excerpt
-     */
-    public function excerpt(string $text, string $phrase, int $radius = 100, string $ending = '...'): string
-    {
-        return $this->_engine->excerpt($text, $phrase, $radius, $ending);
-    }
-
-    /**
-     * Creates a comma separated list where the last two items are joined with 'and', forming natural language.
-     *
-     * @param array<string> $list The list to be joined.
-     * @param string|null $and The word used to join the last and second last items together with. Defaults to 'and'.
-     * @param string $separator The separator used to join all the other items together. Defaults to ', '.
-     * @return string The glued together string.
-     * @see \Cake\Utility\Text::toList()
-     * @link https://book.cakephp.org/4/en/views/helpers/text.html#converting-an-array-to-sentence-form
-     */
-    public function toList(array $list, ?string $and = null, string $separator = ', '): string
-    {
-        return $this->_engine->toList($list, $and, $separator);
-    }
-
-    /**
-     * Returns a string with all spaces converted to dashes (by default),
-     * characters transliterated to ASCII characters, and non word characters removed.
-     *
-     * ### Options:
-     *
-     * - `replacement`: Replacement string. Default '-'.
-     * - `transliteratorId`: A valid transliterator id string.
-     *   If `null` (default) the transliterator (identifier) set via
-     *   `Text::setTransliteratorId()` or `Text::setTransliterator()` will be used.
-     *   If `false` no transliteration will be done, only non words will be removed.
-     * - `preserve`: Specific non-word character to preserve. Default `null`.
-     *   For e.g. this option can be set to '.' to generate clean file names.
-     *
-     * @param string $string the string you want to slug
-     * @param array|string $options If string it will be use as replacement character
-     *   or an array of options.
-     * @return string
-     * @see \Cake\Utility\Text::setTransliterator()
-     * @see \Cake\Utility\Text::setTransliteratorId()
-     */
-    public function slug(string $string, array|string $options = []): string
-    {
-        return $this->_engine->slug($string, $options);
-    }
-
-    /**
      * Event listeners.
      *
      * @return array<string, mixed>

+ 7 - 56
tests/TestCase/View/Helper/NumberHelperTest.php

@@ -18,16 +18,9 @@ declare(strict_types=1);
  */
 namespace Cake\Test\TestCase\View\Helper;
 
-use Cake\Core\Configure;
-use Cake\I18n\Number;
 use Cake\TestSuite\TestCase;
 use Cake\View\Helper\NumberHelper;
 use Cake\View\View;
-use ReflectionMethod;
-use TestApp\Utility\NumberMock;
-use TestApp\Utility\TestAppEngine;
-use TestApp\View\Helper\NumberHelperTestObject;
-use TestPlugin\Utility\TestPluginEngine;
 
 /**
  * NumberHelperTest class
@@ -47,7 +40,6 @@ class NumberHelperTest extends TestCase
         parent::setUp();
         $this->View = new View();
 
-        $this->_appNamespace = Configure::read('App.namespace');
         static::setAppNamespace();
     }
 
@@ -58,7 +50,6 @@ class NumberHelperTest extends TestCase
     {
         parent::tearDown();
         $this->clearPlugins();
-        static::setAppNamespace($this->_appNamespace);
         unset($this->View);
     }
 
@@ -70,60 +61,20 @@ class NumberHelperTest extends TestCase
     public function methodProvider(): array
     {
         return [
-            ['precision'],
-            ['toReadableSize'],
-            ['toPercentage'],
-            ['currency'],
-            ['format'],
-            ['formatDelta'],
-            ['ordinal'],
+            ['precision', 1.23],
+            ['toReadableSize', 1.23],
+            ['toPercentage', 1.23],
         ];
     }
 
     /**
-     * test CakeNumber class methods are called correctly
+     * Tests calls are proxied to Number class.
      *
      * @dataProvider methodProvider
      */
-    public function testNumberHelperProxyMethodCalls(string $method): void
+    public function testMethodProxying(string $method, mixed $arg): void
     {
-        $number = $this->getMockBuilder(NumberMock::class)
-            ->addMethods([$method])
-            ->getMock();
-        $helper = new NumberHelperTestObject($this->View, ['engine' => NumberMock::class]);
-        $helper->attach($number);
-        $number->expects($this->once())
-            ->method($method)
-            ->with(12.3)
-            ->willReturn('');
-        $helper->{$method}(12.3);
-    }
-
-    /**
-     * Test that number of argument of helper's proxy methods matches
-     * corresponding method of Number class.
-     *
-     * @dataProvider methodProvider
-     */
-    public function testParameterCountMatch(string $method): void
-    {
-        $numberMethod = new ReflectionMethod(Number::class, $method);
-        $helperMethod = new ReflectionMethod(NumberHelper::class, $method);
-
-        $this->assertSame($numberMethod->getNumberOfParameters(), $helperMethod->getNumberOfParameters());
-    }
-
-    /**
-     * test engine override
-     */
-    public function testEngineOverride(): void
-    {
-        $Number = new NumberHelperTestObject($this->View, ['engine' => 'TestAppEngine']);
-        $this->assertInstanceOf(TestAppEngine::class, $Number->engine());
-
-        $this->loadPlugins(['TestPlugin']);
-        $Number = new NumberHelperTestObject($this->View, ['engine' => 'TestPlugin.TestPluginEngine']);
-        $this->assertInstanceOf(TestPluginEngine::class, $Number->engine());
-        $this->removePlugins(['TestPlugin']);
+        $helper = new NumberHelper($this->View);
+        $this->assertNotNull($helper->{$method}($arg));
     }
 }

+ 14 - 96
tests/TestCase/View/Helper/TextHelperTest.php

@@ -20,10 +20,6 @@ use Cake\Core\Configure;
 use Cake\TestSuite\TestCase;
 use Cake\View\Helper\TextHelper;
 use Cake\View\View;
-use TestApp\Utility\TestAppEngine;
-use TestApp\Utility\TextMock;
-use TestApp\View\Helper\TextHelperTestObject;
-use TestPlugin\Utility\TestPluginEngine;
 
 /**
  * TextHelperTest class
@@ -64,75 +60,28 @@ class TextHelperTest extends TestCase
     }
 
     /**
-     * test String class methods are called correctly
+     * Provider for method proxying.
+     *
+     * @return array
      */
-    public function testTextHelperProxyMethodCalls(): void
+    public function methodProvider(): array
     {
-        $methods = [
-            'stripLinks', 'toList',
-        ];
-        $String = $this->getMockBuilder(TextMock::class)
-            ->addMethods($methods)
-            ->getMock();
-        $Text = new TextHelperTestObject($this->View, ['engine' => TextMock::class]);
-        $Text->attach($String);
-        foreach ($methods as $method) {
-            $String->expects($this->once())->method($method)->willReturn('');
-            $Text->{$method}(['who'], 'what', 'when', 'where', 'how');
-        }
-
-        $methods = [
-            'excerpt',
-        ];
-        $String = $this->getMockBuilder(TextMock::class)
-            ->addMethods($methods)
-            ->getMock();
-        $Text = new TextHelperTestObject($this->View, ['engine' => TextMock::class]);
-        $Text->attach($String);
-        foreach ($methods as $method) {
-            $String->expects($this->once())->method($method)->willReturn('');
-            $Text->{$method}('who', 'what');
-        }
-
-        $methods = [
-            'highlight',
-        ];
-        $String = $this->getMockBuilder(TextMock::class)
-            ->addMethods($methods)
-            ->getMock();
-        $Text = new TextHelperTestObject($this->View, ['engine' => TextMock::class]);
-        $Text->attach($String);
-        foreach ($methods as $method) {
-            $String->expects($this->once())->method($method)->willReturn('');
-            $Text->{$method}('who', 'what');
-        }
-
-        $methods = [
-            'tail', 'truncate',
+        return [
+            ['highlight', ['this is a test', 'test']],
+            ['slug', ['test']],
+            ['tail', ['test test']],
         ];
-        $String = $this->getMockBuilder(TextMock::class)
-            ->addMethods($methods)
-            ->getMock();
-        $Text = new TextHelperTestObject($this->View, ['engine' => TextMock::class]);
-        $Text->attach($String);
-        foreach ($methods as $method) {
-            $String->expects($this->once())->method($method)->willReturn('');
-            $Text->{$method}('who', 1, ['what']);
-        }
     }
 
     /**
-     * test engine override
+     * Tests calls are proxied to Number class.
+     *
+     * @dataProvider methodProvider
      */
-    public function testEngineOverride(): void
+    public function testMethodProxying(string $method, mixed $arg): void
     {
-        $Text = new TextHelperTestObject($this->View, ['engine' => 'TestAppEngine']);
-        $this->assertInstanceOf(TestAppEngine::class, $Text->engine());
-
-        $this->loadPlugins(['TestPlugin']);
-        $Text = new TextHelperTestObject($this->View, ['engine' => 'TestPlugin.TestPluginEngine']);
-        $this->assertInstanceOf(TestPluginEngine::class, $Text->engine());
-        $this->clearPlugins();
+        $helper = new TextHelper($this->View);
+        $this->assertNotNull($helper->{$method}(...$arg));
     }
 
     /**
@@ -606,35 +555,4 @@ TEXT;
         $result = $this->Text->autoParagraph(null);
         $this->assertTextEquals($expected, $result);
     }
-
-    /**
-     * testSlug method
-     *
-     * @param string $string String
-     * @param array $options Options
-     * @param String $expected Expected string
-     * @dataProvider slugInputProvider
-     */
-    public function testSlug($string, $options, $expected): void
-    {
-        $result = $this->Text->slug($string, $options);
-        $this->assertSame($expected, $result);
-    }
-
-    /**
-     * @return array
-     */
-    public function slugInputProvider(): array
-    {
-        return [
-            [
-                'Foo Bar: Not just for breakfast any-more', [],
-                'Foo-Bar-Not-just-for-breakfast-any-more',
-            ],
-            [
-                'Foo Bar: Not just for breakfast any-more', ['replacement' => false],
-                'FooBarNotjustforbreakfastanymore',
-            ],
-        ];
-    }
 }

+ 0 - 8
tests/test_app/Plugin/TestPlugin/src/Utility/TestPluginEngine.php

@@ -1,8 +0,0 @@
-<?php
-declare(strict_types=1);
-
-namespace TestPlugin\Utility;
-
-class TestPluginEngine
-{
-}

+ 0 - 8
tests/test_app/TestApp/Utility/NumberMock.php

@@ -1,8 +0,0 @@
-<?php
-declare(strict_types=1);
-
-namespace TestApp\Utility;
-
-class NumberMock
-{
-}

+ 0 - 8
tests/test_app/TestApp/Utility/TestAppEngine.php

@@ -1,8 +0,0 @@
-<?php
-declare(strict_types=1);
-
-namespace TestApp\Utility;
-
-class TestAppEngine
-{
-}

+ 0 - 8
tests/test_app/TestApp/Utility/TextMock.php

@@ -1,8 +0,0 @@
-<?php
-declare(strict_types=1);
-
-namespace TestApp\Utility;
-
-class TextMock
-{
-}

+ 0 - 26
tests/test_app/TestApp/View/Helper/NumberHelperTestObject.php

@@ -1,26 +0,0 @@
-<?php
-declare(strict_types=1);
-
-namespace TestApp\View\Helper;
-
-use Cake\View\Helper\NumberHelper;
-use TestApp\Utility\NumberMock;
-
-/**
- * NumberHelperTestObject class
- */
-class NumberHelperTestObject extends NumberHelper
-{
-    public function attach(NumberMock $cakeNumber): void
-    {
-        $this->_engine = $cakeNumber;
-    }
-
-    /**
-     * @return mixed
-     */
-    public function engine()
-    {
-        return $this->_engine;
-    }
-}

+ 0 - 23
tests/test_app/TestApp/View/Helper/TextHelperTestObject.php

@@ -1,23 +0,0 @@
-<?php
-declare(strict_types=1);
-
-namespace TestApp\View\Helper;
-
-use Cake\View\Helper\TextHelper;
-use TestApp\Utility\TextMock;
-
-class TextHelperTestObject extends TextHelper
-{
-    public function attach(TextMock $string): void
-    {
-        $this->_engine = $string;
-    }
-
-    /**
-     * @return mixed
-     */
-    public function engine()
-    {
-        return $this->_engine;
-    }
-}