瀏覽代碼

Initial release of PHP Flash library

michelphp 23 小時之前
當前提交
dc8557ee92
共有 6 個文件被更改,包括 270 次插入0 次删除
  1. 4 0
      .gitignore
  2. 21 0
      LICENSE
  3. 62 0
      README.md
  4. 23 0
      composer.json
  5. 84 0
      src/Flash.php
  6. 76 0
      tests/FlashTest.php

+ 4 - 0
.gitignore

@@ -0,0 +1,4 @@
+/vendor/
+/.idea/
+.phpunit.result.cache
+composer.lock

+ 21 - 0
LICENSE

@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2023 F. Michel
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.

+ 62 - 0
README.md

@@ -0,0 +1,62 @@
+# Michel PHP Flash
+
+PHP Flash is a lightweight library for managing message flash functionality in PHP applications. It allows you to easily display temporary messages, such as success messages, warnings, and error notifications, to enhance the user experience.
+
+## Features
+
+- Simple and intuitive message flash management.
+- Display success messages, warnings, and error notifications.
+- Automatic clearing of messages after retrieval.
+
+## Installation
+
+To install PHP Flash, use [Composer](https://getcomposer.org/):
+
+```bash
+composer require michel/flash
+```
+
+## Usage
+
+### Basic Usage
+
+```php
+use Michel\Flash\Flash;
+
+// Assuming you already have session_start() called in your script
+$flash = new Flash($_SESSION);
+
+// Set flash messages
+$flash->set('success', 'Operation completed successfully.');
+$flash->set('error', 'An error occurred.');
+// OR
+$flash->success('Operation completed successfully.');
+$flash->error('An error occurred.');
+
+// Get and display flash messages
+if ($message = $flash->get('success')) {
+    echo '<div class="success">' . $message . '</div>';
+}
+
+if ($message = $flash->get('error')) {
+    echo '<div class="error">' . $message . '</div>';
+}
+```
+
+### Custom Flash Key
+
+By default, PHP Flash uses the key "__flash" in the session storage. You can use a custom key if needed:
+
+```php
+// Assuming you already have session_start() called in your script
+$customFlashKey = 'my_custom_flash_key';
+$flash = new Flash($_SESSION, $customFlashKey);
+```
+
+## Contribution
+
+Contributions are welcome! If you find any issues or have suggestions, please open an issue or submit a pull request.
+
+## License
+
+PHP Flash is open-source software licensed under the [MIT license](https://opensource.org/licenses/MIT).

+ 23 - 0
composer.json

@@ -0,0 +1,23 @@
+{
+  "name": "michel/flash",
+  "description": "PHP Flash is a lightweight library for managing message flash functionality in PHP applications. It allows you to easily display temporary messages, such as success messages, warnings, and error notifications, to enhance the user experience.",
+  "type": "library",
+  "require": {
+    "php": ">=7.4"
+  },
+  "license": "MIT",
+  "authors": [
+    {
+      "name": "Michel.F"
+    }
+  ],
+  "autoload": {
+    "psr-4": {
+      "Michel\\Flash\\": "src",
+      "Test\\Michel\\Flash\\": "tests"
+    }
+  },
+  "require-dev": {
+    "michel/unitester": "^1.0.0"
+  }
+}

+ 84 - 0
src/Flash.php

@@ -0,0 +1,84 @@
+<?php
+
+declare(strict_types=1);
+
+namespace Michel\Flash;
+
+use ArrayAccess;
+use InvalidArgumentException;
+use function array_key_exists;
+use function is_array;
+
+final class Flash
+{
+    private const DEFAULT_FLASH_KEY = '__flash';
+
+    /**
+     * @var array|ArrayAccess
+     */
+    private $storage;
+    /**
+     * @var string
+     */
+    private string $key;
+
+    public function __construct(&$storage, string $key = self::DEFAULT_FLASH_KEY)
+    {
+        if (!$storage instanceof ArrayAccess && !is_array($storage)) {
+            throw new InvalidArgumentException('storage argument must be an array or instance of ArrayAccess');
+        }
+        $this->storage = &$storage;
+        $this->key = $key;
+    }
+
+    public function success( string $message) : void
+    {
+        $this->set('success', $message);
+    }
+
+    public function error( string $message) : void
+    {
+        $this->set('error', $message);
+    }
+
+    public function warning( string $message) : void
+    {
+        $this->set('warning', $message);
+    }
+
+    public function info( string $message) : void
+    {
+        $this->set('info', $message);
+    }
+
+    public function set(string $type, string $message): void
+    {
+        $messages = $this->getInStorage();
+        $messages[$type] = $message;
+        $this->setInStorage($messages);
+    }
+
+    public function get(string $type): ?string
+    {
+        $messages = $this->getInStorage();
+        if (!array_key_exists($type, $messages)) {
+            return null;
+        }
+
+        $message = $messages[$type];
+        unset($messages[$type]);
+        $this->setInStorage($messages);
+
+        return $message;
+    }
+
+    private function getInStorage(): array
+    {
+        return $this->storage[$this->key] ?? [];
+    }
+
+    private function setInStorage($value): void
+    {
+        $this->storage[$this->key] = $value;
+    }
+}

+ 76 - 0
tests/FlashTest.php

@@ -0,0 +1,76 @@
+<?php
+
+namespace Test\Michel\Flash;
+
+use ArrayObject;
+use InvalidArgumentException;
+use Michel\Flash\Flash;
+use Michel\UniTester\TestCase;
+
+final class FlashTest extends TestCase
+{
+    private array $storage;
+    private Flash $flash;
+
+    protected function tearDown(): void
+    {
+        // TODO: Implement tearDown() method.
+    }
+
+    protected function execute(): void
+    {
+        $this->testSetAndGetFlashMessage();
+        $this->testGetNonExistentFlashMessage();
+        $this->testFlashMessageShouldBeClearedAfterGet();
+        $this->testInvalidStorageArgument();
+        $this->testCustomFlashKey();
+    }
+
+    protected function setUp(): void
+    {
+        $this->storage = [];
+        $this->flash = new Flash($this->storage);
+    }
+
+    public function testSetAndGetFlashMessage(): void
+    {
+        $this->flash->set('success', 'Operation completed successfully.');
+        $this->flash->set('error', 'An error occurred.');
+
+        $this->assertEquals('Operation completed successfully.', $this->flash->get('success'));
+        $this->assertEquals('An error occurred.', $this->flash->get('error'));
+    }
+
+    public function testGetNonExistentFlashMessage(): void
+    {
+        $this->assertNull($this->flash->get('warning'));
+    }
+
+    public function testFlashMessageShouldBeClearedAfterGet(): void
+    {
+        $this->flash->set('info', 'This is an informational message.');
+
+        // Get the flash message, should return the message
+        $this->assertEquals('This is an informational message.', $this->flash->get('info'));
+
+        // Try getting the same message again, should be null as it was cleared after get
+        $this->assertNull($this->flash->get('info'));
+    }
+
+    public function testInvalidStorageArgument(): void
+    {
+        $this->expectException(InvalidArgumentException::class, function () {
+            $invalid = 'invalid';
+            new Flash($invalid, 'custom_key');
+        });
+    }
+
+    public function testCustomFlashKey(): void
+    {
+        $customStorage = new ArrayObject();
+        $flash = new Flash($customStorage, 'my_custom_flash_key');
+        $flash->set('message', 'Custom flash key test.');
+
+        $this->assertEquals('Custom flash key test.', $flash->get('message'));
+    }
+}