diff --git a/.codeclimate.yml b/.codeclimate.yml new file mode 100644 index 0000000..6625bbc --- /dev/null +++ b/.codeclimate.yml @@ -0,0 +1,28 @@ +engines: + duplication: + enabled: true + config: + languages: + php: + mass_threshold: 40 + fixme: + enabled: true + phpmd: + enabled: true + checks: + CleanCode/StaticAccess: + enabled: false + CleanCode/BooleanArgumentFlag: + enabled: false + Design/TooManyPublicMethods: + enabled: false + Design/CouplingBetweenObjects: + enabled: false +ratings: + paths: + - "src/Notifynder/**.php" +exclude_paths: + - tests/ + - spec/ + - src/migrations/ + - src/config/ diff --git a/.coveralls.yml b/.coveralls.yml new file mode 100644 index 0000000..b81810c --- /dev/null +++ b/.coveralls.yml @@ -0,0 +1,3 @@ +coverage_clover: build/logs/clover.xml +json_path: build/logs/coveralls-upload.json +service_name: travis-ci \ No newline at end of file diff --git a/.gitignore b/.gitignore index 0679353..74333e2 100755 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,3 @@ /vendor composer.lock -.idea \ No newline at end of file +/build \ No newline at end of file diff --git a/.scrutinizer.yml b/.scrutinizer.yml new file mode 100644 index 0000000..a76e4e7 --- /dev/null +++ b/.scrutinizer.yml @@ -0,0 +1,9 @@ +checks: + php: true +filter: + paths: ["src/Notifynder/*"] + excluded_paths: + - tests/* +build: + environment: + php: 7.0.6 \ No newline at end of file diff --git a/.styleci.yml b/.styleci.yml new file mode 100644 index 0000000..7096010 --- /dev/null +++ b/.styleci.yml @@ -0,0 +1,5 @@ +preset: laravel + +risky: false + +linting: true diff --git a/.travis.yml b/.travis.yml index bb79058..a8c9834 100755 --- a/.travis.yml +++ b/.travis.yml @@ -1,15 +1,59 @@ language: php +## Run on container environment +sudo: false + +## Cache composer bits +cache: + directories: + - $HOME/.composer/cache + +## Addons used by this package +addons: + code_climate: + repo_token: ${CC_TOKEN} + +## List all PHP versions to test with php: - 5.5 - 5.6 - - hhvm + - 7.0 -before_script: +## Define all ENV vars to test with +env: + - LARAVEL_VERSION="5.0.*" + - LARAVEL_VERSION="5.1.*" + - LARAVEL_VERSION="5.2.*" + - LARAVEL_VERSION="5.3.*" + +matrix: + exclude: + - php: 5.5 + env: LARAVEL_VERSION="5.3.*" + +## Install Dependencies +install: - composer self-update - - composer install --prefer-source --no-interaction + - if [ -n "$GH_TOKEN" ]; then composer config github-oauth.github.com ${GH_TOKEN}; fi; + - composer require laravel/framework:${LARAVEL_VERSION} --no-update --no-interaction + - composer install --prefer-dist --no-interaction + +## Run Scripts before Tests +before_script: - composer dump-autoload -o +## Run test Scripts script: - - vendor/bin/phpspec run - - vendor/bin/phpunit \ No newline at end of file + - vendor/bin/phpunit + - php CoverageChecker.php build/logs/clover.xml 80 + +after_script: + - vendor/bin/test-reporter + - export CI_BUILD_NUMBER="$TRAVIS_BUILD_NUMBER" + - export CI_PULL_REQUEST="$TRAVIS_PULL_REQUEST" + - export CI_BRANCH="$TRAVIS_BRANCH" + - vendor/bin/coveralls -v + +## Send Build Notifications to Slack +notifications: + slack: notifynder:CnF7P2xaZuJTJ4VzNOy6ksDH \ No newline at end of file diff --git a/CoverageChecker.php b/CoverageChecker.php new file mode 100644 index 0000000..5a4c2c6 --- /dev/null +++ b/CoverageChecker.php @@ -0,0 +1,33 @@ +xpath('//metrics'); +$totalElements = 0; +$checkedElements = 0; + +foreach ($metrics as $metric) { + $totalElements += (int) $metric['elements']; + $checkedElements += (int) $metric['coveredelements']; +} + +$coverage = ($checkedElements / $totalElements) * 100; + +if ($coverage < $percentage) { + echo 'Code coverage is '.$coverage.'%, which is below the accepted '.$percentage.'%'.PHP_EOL; + exit(1); +} + +echo 'Code coverage is '.$coverage.'% - OK!'.PHP_EOL; diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..405477b --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Fabrizio + +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. diff --git a/README.md b/README.md index 3641546..ed1a88f 100755 --- a/README.md +++ b/README.md @@ -1,95 +1,126 @@ -Notifynder 3.0 - Laravel 5 -========== +# Notifynder 4 - Laravel 5 + +[![GitHub release](https://img.shields.io/github/release/fenos/Notifynder.svg?style=flat-square)](https://github.com/fenos/Notifynder/releases) +[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](https://raw.githubusercontent.com/fenos/Notifynder/master/LICENSE) +[![GitHub issues](https://img.shields.io/github/issues/fenos/Notifynder.svg?style=flat-square)](https://github.com/fenos/Notifynder/issues) +[![Total Downloads](https://img.shields.io/packagist/dt/fenos/notifynder.svg?style=flat-square)](https://packagist.org/packages/fenos/notifynder) + +[![Travis branch](https://img.shields.io/travis/fenos/Notifynder/master.svg?style=flat-square&label=TravisCI)](https://travis-ci.org/fenos/Notifynder/branches) +[![StyleCI](https://styleci.io/repos/18425539/shield)](https://styleci.io/repos/18425539) +[![Scrutinizer Build](https://img.shields.io/scrutinizer/build/g/fenos/Notifynder.svg?style=flat-square&label=ScrutinizerCI)](https://scrutinizer-ci.com/g/fenos/Notifynder/?branch=master) + +[![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/g/fenos/Notifynder.svg?style=flat-square)](https://scrutinizer-ci.com/g/fenos/Notifynder/?branch=master) +[![Code Climate](https://img.shields.io/codeclimate/github/fenos/Notifynder.svg?style=flat-square)](https://codeclimate.com/github/fenos/Notifynder) +[![Coveralls](https://img.shields.io/coveralls/fenos/Notifynder.svg?style=flat-square)](https://coveralls.io/github/fenos/Notifynder) + +[![Slack Team](https://img.shields.io/badge/slack-astrotomic-orange.svg?style=flat-square)](https://astrotomic.slack.com) +[![Slack join](https://img.shields.io/badge/slack-join-green.svg?style=social)](https://notifynder.signup.team) -[![Build Status](https://travis-ci.org/fenos/Notifynder.svg?branch=master)](https://travis-ci.org/fenos/Notifynder) -[![ProjectStatus](http://stillmaintained.com/fenos/Notifynder.png)](http://stillmaintained.com/fenos/Notifynder) -[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/fenos/Notifynder/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/fenos/Notifynder/?branch=master) -[![Total Downloads](https://poser.pugx.org/fenos/notifynder/downloads.svg)](https://packagist.org/packages/fenos/notifynder) -[![License](https://poser.pugx.org/fenos/Notifynder/license.png)](https://packagist.org/packages/fenos/Notifynder) -[![Latest Stable Version](https://poser.pugx.org/fenos/notifynder/v/stable.png)](https://packagist.org/packages/fenos/notifynder) Notifynder is designed to manage notifications in a powerful and easy way. With the flexibility that Notifynder offer, It provide a complete API to work with your notifications, -such as storing, retriving, and organise your codebase to handle hundreds of notifications. +such as storing, retrieving, and organise your codebase to handle hundreds of notifications. You get started in a couple of minutes to "enable" notifications in your Laravel Project. Compatible DBs: **MySql** - **PostgresSql** - **Sqlite** -Documentation: **[Notifynder Wiki](https://github.com/fenos/Notifynder/wiki)** -- - - +Documentation: **[Notifynder Docu](http://notifynder.info)** + +----- -## Installation ## +## Installation -### Step 1 ### +### Step 1 -Add it on your composer.json +Add it on your `composer.json` -~~~ -"fenos/notifynder": "3.*" -~~~ +``` +"fenos/notifynder": "^4.0" +``` -and run **composer update** +and run +``` +composer update +``` -### Step 2 ### +or run -Add the following string to **config/app.php** +``` +composer require fenos/notifynder +``` + + +### Step 2 + +Add the following string to `config/app.php` **Providers array:** -~~~ -'Fenos\Notifynder\NotifynderServiceProvider' -~~~ +``` +Fenos\Notifynder\NotifynderServiceProvider::class, +``` **Aliases array:** -~~~ -'Notifynder' => 'Fenos\Notifynder\Facades\Notifynder' -~~~ +``` +'Notifynder' => Fenos\Notifynder\Facades\Notifynder::class, +``` + -### Step 3 ### +### Step 3 -#### Migration #### +#### Migration & Config Publish the migration as well as the configuration of notifynder with the following command: -~~~ +``` php artisan vendor:publish --provider="Fenos\Notifynder\NotifynderServiceProvider" -~~~ +``` + +Run the migration + +``` +php artisan migrate +``` + +## Usage + +This Branch isn't ready for any kind of usage! It's development in progress and will bring a whole new code-base for this package. +Everyone is welcome to support us or give feedback for the new major version in our Slack Team. + +### ToDo + +Tasks we have to do until this version is ready for a stable release: + +* add unittests for parser and models +* complete the new documentation + + +## Versioning -Don't forget to migrate. +Starting with `v4.0.0` we are following the [Semantic Versioning Standard](http://semver.org). -### Quick Usage ### +### Summary -Set up category of notification, think about it as the -body of the notification: +Given a version number `MAJOR`.`MINOR`.`PATCH`, increment the: -~~~ -php artisan notifynder:create:category "user.following" "{from.username} started to follow you" -~~~ +* **MAJOR** version when you make incompatible API changes, +* **MINOR** version when you add functionality in a backwards-compatible manner, and +* **PATCH** version when you make backwards-compatible bug fixes. -To send a notification with notifynder, that's all -you have to do. +Additional labels for pre-release (`alpha`, `beta`, `rc`) are available as extensions to the `MAJOR`.`MINOR`.`PATCH` format. -~~~ -Notifynder::category('user.following') - ->from($from_user_id) - ->to($to_user_id) - ->url('http://www.yourwebsite.com/page') - ->send(); -~~~ +## Contributors -**Retrieving Notifications** +Thanks for everyone [who contributed](https://github.com/fenos/Notifynder/graphs/contributors) to Notifynder and a special thanks for the most active contributors -~~~ -// @return Collection -Notifynder::getAll($user_id,$limit,$paginateBool); -~~~ +- [Gummibeer](https://github.com/Gummibeer) -**Reading Notifications:** -~~~ -// @return number of notifications read -Notifynder::ReadAll($user_id); -~~~ +## Services -To know more, such as the advance usage of Notifynder Visit the **[Notifynder Wiki](https://github.com/fenos/Notifynder/wiki)**. +* [Travis CI](https://travis-ci.org/fenos/Notifynder) +* [Style CI](https://styleci.io/repos/18425539) +* [Code Climate](https://codeclimate.com/github/fenos/Notifynder) +* [Scrutinizer](https://scrutinizer-ci.com/g/fenos/Notifynder) +* [Coveralls](https://coveralls.io/github/fenos/Notifynder) \ No newline at end of file diff --git a/change.log b/change.log deleted file mode 100755 index 0b8699b..0000000 --- a/change.log +++ /dev/null @@ -1,60 +0,0 @@ -Notifynder v. 3.0 Change log: - -- Rewrote every UnitTest in PhpSpec - -- Rewrote Main classes with TDD and PHPSpec - -- Rewrote integration test with better organisation and examples - -- Added foreign key to the category_id in notification table / Migration. - -- Compact configuration in one unique file app/config/notifynder.php - -- Added Contracts. It follow the way of laravel 5, each main class has their own contracts - it will be useful to remove encapsulation and to overwtire implementations through IoC - -- Optimization NotifynderBuilder, it doesn't use reflection any more to build the array. - i felt weird that I used reflection for generate an array ( now more fast). - - - Renamed method getArray() in toArray() of the builder - -- Renamed NotifynderNotification to NotifynderManager and extracted it to an interface - with the previous name of the class "NotifynderNotification" - -- Rename NotifynderCategory to CategoryManager and extract it functionalities to an interface - called as the previous class "NotifynderCategory" - -- Translations are now cached on the folder storage/app/notifynder - -- Renamed NotifynderTranslator to TranslatorManager with interface NotifynderTranslator - -- Notifynder Senders can now be extended! You can create your custom Senders. - -- Improvement Notifynder Dispatcher/Handler, - - - Rename the Dispatcher to be Handler (More consistent name) - - Rename the Handler to be Dispatcher (More consistent name) - - The Handler doesn't receive arrays any more but NotifynderEvent object - - Get extra data from the NotifynderEvent Object $event->get('name'), $event->name - - Events are now registered under the Notifynder.* wildcard - - Events can be called with . or @ convention ex: user.registerd - user@registered - - Listeners are defined in the EventServiceProvider with a different property, ex. $notifications - and those listeners are booted with Notifynder::bootListeners($this->notifications) - -- Removed queue system at the moment, I want to think something cool for it, using - The way of laravel 5 will be implemented in notifynder v 3.1.0 - -- fixed method on issue: https://github.com/fenos/Notifynder/issues/22 - -- Added order be date when retrieving notifications, issue: https://github.com/fenos/Notifynder/issues/19 - -- Builder is now part of the Notifynder class, you can access to the builder directly from the Notifynder - class and you can chain your custom and default method for send the notification! Cool! - -- You can now compose and send your notification in one go! - -- Improved EventHandler to be working with a native way of using events - in Laravel 5 - -- No need queue anymore, You can use Laravel ShouldBeQueue - Interface in your events! \ No newline at end of file diff --git a/composer.json b/composer.json index 6f09e3a..2561193 100755 --- a/composer.json +++ b/composer.json @@ -8,18 +8,26 @@ "name": "Fabrizio Fenoglio", "email": "fabri_feno@yahoo.it", "role": "Developer" + }, + { + "name": "Tom Witkowski", + "email": "dev.gummibeer@gmail.com", + "role": "Developer" } ], "require": { "php": ">=5.5.0", - "illuminate/support": "5.*" + "illuminate/support": "~5.0" }, "require-dev": { - "laravel/framework": "5.0.*", + "laravel/framework": "~5.0", "phpunit/phpunit": "~4.0", "phpspec/phpspec": "~2.1", "laracasts/testdummy": "~2.0", - "orchestra/testbench": "3.0.*" + "orchestra/testbench": "~3.0", + "doctrine/dbal": "^2.5", + "codeclimate/php-test-reporter": "^0.3.2", + "satooshi/php-coveralls": "^1.0" }, "autoload": { "classmap": [ @@ -27,11 +35,15 @@ ], "psr-4": { "Fenos\\Notifynder\\": "src/Notifynder" - } + }, + "files": [ + + "src/Notifynder/Helpers/helpers.php" + ] }, "autoload-dev": { "classmap": [ - "tests/TestCaseDB.php" + "tests/NotifynderTestCase.php" ], "psr-4": { "Fenos\\Tests\\": "tests/models" diff --git a/phpunit.xml b/phpunit.xml index dc51e81..ebefb65 100755 --- a/phpunit.xml +++ b/phpunit.xml @@ -14,6 +14,21 @@ ./tests/integration + + + ./src/Notifynder + + + ./vendor + ./tests + ./spec + ./build + + + + + + diff --git a/spec/.gitkeep b/spec/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/spec/Fenos/Notifynder/Builder/NotifynderBuilderSpec.php b/spec/Fenos/Notifynder/Builder/NotifynderBuilderSpec.php deleted file mode 100755 index 3c609ea..0000000 --- a/spec/Fenos/Notifynder/Builder/NotifynderBuilderSpec.php +++ /dev/null @@ -1,172 +0,0 @@ -beConstructedWith($category); - } - - function it_is_initializable() - { - $this->shouldHaveType('Fenos\Notifynder\Builder\NotifynderBuilder'); - } - - /** @test */ - function it_set_the_FROM_value_with_a_single_entity() - { - $user_id = 1; - - $this->from($user_id)->shouldReturnAnInstanceOf(NotifynderBuilder::class); - } - - /** @test */ - function it_set_the_FROM_value_giving_a_polymorphic_entity() - { - $user_id = 1; - $user_class = 'User'; - - $this->from($user_class,$user_id)->shouldReturnAnInstanceOf(NotifynderBuilder::class); - } - - /** @test */ - function it_set_the_FROM_value_giving_a_polymorphic_entity_the_first_value_must_be_the_class_entity() - { - $user_id = 1; - $user_class = 'User'; - - $this->shouldThrow('InvalidArgumentException')->during('from',[$user_id,$user_class]); - } - - /** @test */ - function it_set_the_TO_value_with_a_single_entity() - { - $user_id = 1; - - $this->to($user_id)->shouldReturnAnInstanceOf(NotifynderBuilder::class); - } - - /** @test */ - function it_set_the_TO_value_giving_a_polymorphic_entity() - { - $user_id = 1; - $user_class = 'User'; - - $this->to($user_class,$user_id)->shouldReturnAnInstanceOf(NotifynderBuilder::class); - } - - /** @test */ - function it_set_the_TO_value_giving_a_polymorphic_entity_the_first_value_must_be_the_class_entity() - { - $user_id = 1; - $user_class = 'User'; - - $this->shouldThrow('InvalidArgumentException')->during('to',[$user_id,$user_class]); - } - - /** @test */ - function it_add_the_url_parameter_to_the_builder() - { - $url = 'www.notifynder.io'; - - $this->url($url)->shouldReturnAnInstanceOf(NotifynderBuilder::class); - } - - /** @test */ - function it_allow_only_string_as_url() - { - $url = 1; - - $this->shouldThrow('InvalidArgumentException')->during('url',[$url]); - } - - /** @test */ - function it_add_the_expire_parameter_to_the_builder() - { - $datetime = new Carbon; - - $this->expire($datetime)->shouldReturnAnInstanceOf(NotifynderBuilder::class); - } - - /** @test */ - function it_allow_only_carbon_instance_as_expire_time() - { - $datetime = 1; - - $this->shouldThrow('InvalidArgumentException')->during('expire',[$datetime]); - } - - - /** @test */ - function it_add_a_category_id_to_the_builder() - { - $category_id = 1; - - $this->category($category_id)->shouldReturnAnInstanceOf(NotifynderBuilder::class); - } - - /** @test */ - function it_add_a_category_id_to_the_builder_givin_the_name_of_it(CategoryManager $category, NotificationCategory $categoryModel) - { - $name = 'category.name'; - $category_id = 1; - - $category->findByName($name)->shouldBeCalled() - ->willReturn($categoryModel); - - $categoryModel->getAttribute('id')->willReturn($category_id); - - $this->category($name)->shouldReturnAnInstanceOf(NotifynderBuilder::class); - } - - /** @test */ - function it_add_the_extra_parameter_to_the_builder() - { - $extra = ['my' => 'extra']; - - $this->extra($extra)->shouldReturnAnInstanceOf(NotifynderBuilder::class); - } - - /** @test */ - function it_allow_only_associative_array_as_extra_parameter_they_llbe_converted_in_jon() - { - $extra = ['my']; - - $this->shouldThrow('InvalidArgumentException')->during('extra',[$extra]); - } - - /** @test */ - function it_create_a_builder_array_using_a_raw_closure() - { - date_default_timezone_set('UTC'); - - $closure = function(NotifynderBuilder $builder) - { - return $builder->to(1)->from(2)->url('notifynder.io')->category(1); - }; - - $this->raw($closure)->shouldHaveKey('to_id'); - $this->raw($closure)->shouldHaveKey('from_id'); - $this->raw($closure)->shouldHaveKey('url'); - $this->raw($closure)->shouldHaveKey('category_id'); - $this->raw($closure)->shouldHaveKey('created_at'); - $this->raw($closure)->shouldHaveKey('updated_at'); - } - - public function it_create_multi_notification_in_a_loop() - { - $cloure = function(NotifynderBuilder $builder,$data,$key) - { - return $builder->to(1)->from(2)->url('notifynder.io')->category(1); - }; - } -} diff --git a/spec/Fenos/Notifynder/Categories/CategoryManagerSpec.php b/spec/Fenos/Notifynder/Categories/CategoryManagerSpec.php deleted file mode 100755 index 706debd..0000000 --- a/spec/Fenos/Notifynder/Categories/CategoryManagerSpec.php +++ /dev/null @@ -1,81 +0,0 @@ -shouldHaveType('Fenos\Notifynder\Categories\CategoryManager'); - } - - public function let(CategoryDB $categoryRepository) - { - $this->beConstructedWith($categoryRepository); - } - - /** @test */ - function it_find_a_category_by_name(CategoryDB $categoryRepository) - { - $nameCategory = 'test.category'; - - $categoryRepository->findByName($nameCategory)->shouldBeCalled() - ->willReturn(new NotificationCategory()); - - $this->findByName($nameCategory)->shouldReturnAnInstanceOf(NotificationCategory::class); - } - - /** @test */ - function it_try_to_find_a_non_existing_category(CategoryDB $categoryRepository) - { - $nameCategory = 'test.category'; - - $categoryRepository->findByName($nameCategory)->shouldBeCalled() - ->willReturn(null); - - $this->shouldThrow(CategoryNotFoundException::class) - ->during('findByName',[$nameCategory]); - } - - /** @test */ - function it_store_a_category(CategoryDB $categoryRepository) - { - $categoryName = 'hello'; - $categoryText = 'wow'; - - $categoryRepository->add($categoryName,$categoryText)->shouldBeCalled() - ->willReturn(new NotificationCategory()); - - $this->add($categoryName,$categoryText)->shouldReturnAnInstanceOf(NotificationCategory::class); - } - - /** @test */ - function it_delete_a_category_by_id(CategoryDB $categoryRepository) - { - $categoryId = 1; - - $categoryRepository->delete($categoryId); - - $categoryRepository->delete($categoryId)->shouldBeCalled() - ->willReturn(1); - - $this->delete($categoryId)->shouldReturn(1); - } - - /** @test */ - function it_delete_a_category_by_name(CategoryDB $categoryRepository) - { - $categoryName = 'testCategory'; - - $categoryRepository->deleteByName($categoryName)->shouldBeCalled() - ->willReturn(1); - - $this->deleteByName($categoryName)->shouldReturn(1); - } -} diff --git a/spec/Fenos/Notifynder/Groups/GroupManagerSpec.php b/spec/Fenos/Notifynder/Groups/GroupManagerSpec.php deleted file mode 100755 index 0efc597..0000000 --- a/spec/Fenos/Notifynder/Groups/GroupManagerSpec.php +++ /dev/null @@ -1,124 +0,0 @@ -beConstructedWith($groupDB,$groupCategoryDB); - } - - function it_is_initializable() - { - $this->shouldHaveType('Fenos\Notifynder\Groups\GroupManager'); - } - - /** @test */ - function it_find_a_group_by_id(NotifynderGroupDB $groupDB, NotificationGroup $group) - { - $group_id = 1; - - $groupDB->find($group_id)->shouldBeCalled() - ->willReturn($group); - - $this->findById($group_id)->shouldReturnAnInstanceOf(NotificationGroup::class); - } - - /** @test */ - function it_try_to_find_an_not_existing_group_by_id(NotifynderGroupDB $groupDB) - { - $group_id = 1; - - $groupDB->find($group_id)->shouldBeCalled() - ->willReturn(null); - - $this->shouldThrow(NotifynderGroupNotFoundException::class)->during('findById',[$group_id]); - } - - /** @test */ - function it_find_a_group_by_name(NotifynderGroupDB $groupDB, NotificationGroup $group) - { - $group_name = 'mygroup'; - - $groupDB->findByName($group_name)->shouldBeCalled() - ->willReturn($group); - - $this->findByName($group_name)->shouldReturnAnInstanceOf(NotificationGroup::class); - } - - /** @test */ - function it_try_to_find_an_not_existing_group_by_name(NotifynderGroupDB $groupDB) - { - $group_name = 'mygroup'; - - $groupDB->findByName($group_name)->shouldBeCalled() - ->willReturn(null); - - $this->shouldThrow(NotifynderGroupNotFoundException::class)->during('findByName',[$group_name]); - } - - /** @test */ - function it_add_a_category_to_a_group_by_id(NotifynderGroupCategoryDB $groupCategoryDB, NotificationGroup $group) - { - $group_id = 1; - $category_id = 2; - - $groupCategoryDB->addCategoryToGroupById($group_id,$category_id)->shouldBeCalled() - ->willReturn($group); - - $this->addCategoryToGroupById($group_id,$category_id)->shouldReturnAnInstanceOf(NotificationGroup::class); - } - - /** @test */ - function it_add_a_category_to_a_group_by_name(NotifynderGroupCategoryDB $groupCategoryDB, NotificationGroup $group) - { - $group_name = 'mygroup'; - $category_name = 'mycategory'; - - $groupCategoryDB->addCategoryToGroupByName($group_name,$category_name)->shouldBeCalled() - ->willReturn($group); - - $this->addCategoryToGroupByName($group_name,$category_name)->shouldReturnAnInstanceOf(NotificationGroup::class); - } - - /** @test */ - function it_add_multiple_categories_to_a_group(NotifynderGroupCategoryDB $groupCategoryDB) - { - $group_name = 'mygroup'; - $category1 = 'mycategory1'; - $category2 = 'mycategory2'; - - $groupCategoryDB->addMultipleCategoriesToGroup($group_name,[$category1,$category2])->shouldBeCalled() - ->willReturn(2); - - $this->addMultipleCategoriesToGroup($group_name,$category1,$category2) - ->shouldReturn(2); - } - - /** @test */ - function it_add_a_group_in_the_db_respecting_convention(NotifynderGroupDB $groupDB,NotificationGroup $group) - { - $name = 'my.category'; - - $groupDB->create($name)->shouldBeCalled() - ->willReturn($group); - - $this->addGroup($name)->shouldReturnAnInstanceOf(NotificationGroup::class); - } - - /** @test */ - function it_add_a_group_in_the_db_NOT_respecting_convention(NotifynderGroupDB $groupDB,NotificationGroup $group) - { - $name = 'mycategory'; // no dot as 'namespace' - - $this->shouldThrow('InvalidArgumentException')->during('addGroup',[$name]); - } -} diff --git a/spec/Fenos/Notifynder/Handler/DispatcherSpec.php b/spec/Fenos/Notifynder/Handler/DispatcherSpec.php deleted file mode 100755 index 5e266ee..0000000 --- a/spec/Fenos/Notifynder/Handler/DispatcherSpec.php +++ /dev/null @@ -1,61 +0,0 @@ -beConstructedWith($dispatcher); - } - - function it_is_initializable() - { - $this->shouldHaveType('Fenos\Notifynder\Handler\Dispatcher'); - } - - /** @test */ - function it_fire_a_notifynder_event(Dispatcher $dispatcher, NotifynderManager $notifynder) - { - $key = 'event'; - $category = 'hello'; - $extraValues = []; - $notifyEvent = 'Notifynder.'.$key; - $notificationBuilt = [ - 0 => ['notification'] - ]; - - $notifynderEvent = new NotifynderEvent($notifyEvent,$category,$extraValues); - - $dispatcher->fire($notifyEvent,[$notifynderEvent,$notifynder])->shouldBeCalled() - ->willReturn($notificationBuilt); - - $notifynder->send($notificationBuilt[0])->shouldBeCalled() - ->willReturn(1); - - $this->fire($notifynder,$key,$category,$extraValues)->shouldReturn(1); - } - - /** @test */ - function it_fire_a_notifynder_event_having_nothing_to_send(Dispatcher $dispatcher, NotifynderManager $notifynder) - { - $key = 'event'; - $category = 'hello'; - $extraValues = []; - $notifyEvent = 'Notifynder.'.$key; - - $notifynderEvent = new NotifynderEvent($notifyEvent,$category,$extraValues); - - $dispatcher->fire($notifyEvent,[$notifynderEvent,$notifynder])->shouldBeCalled() - ->willReturn(null); - - $this->fire($notifynder,$key,$category,$extraValues) - ->shouldReturn(null); - } -} diff --git a/spec/Fenos/Notifynder/Notifications/NotificationManagerSpec.php b/spec/Fenos/Notifynder/Notifications/NotificationManagerSpec.php deleted file mode 100755 index 0ad4550..0000000 --- a/spec/Fenos/Notifynder/Notifications/NotificationManagerSpec.php +++ /dev/null @@ -1,222 +0,0 @@ -beConstructedWith($notificationRepo); - } - - function it_is_initializable() - { - $this->shouldHaveType('Fenos\Notifynder\Notifications\NotificationManager'); - } - - /** @test */ - function it_find_a_notification_by_id(NotificationDB $notificationRepo) - { - $notification_id = 1; - $notification = new Notification(); - - $notificationRepo->find($notification_id)->shouldBeCalled() - ->willReturn($notification); - - $this->find($notification_id)->shouldReturnAnInstanceOf(Notification::class); - } - - /** @test */ - function it_try_to_find_an_inexistent_notification(NotificationDB $notificationRepo) - { - $notification_id = 1; - - $notificationRepo->find($notification_id)->shouldBeCalled() - ->willReturn(null); - - $this->shouldThrow(NotificationNotFoundException::class)->during('find',[$notification_id]); - } - - /** @test */ - function it_read_one_notification_by_id(NotificationDB $notificationRepo) - { - $notification_id = 1; - $notification = new Notification(); - - $notificationRepo->find($notification_id)->shouldBeCalled() - ->willReturn($notification); - - $notificationRepo->readOne($notification)->shouldBeCalled() - ->willReturn($notification); - - $this->readOne($notification_id)->shouldReturnAnInstanceOf($notification); - } - - /** @test */ - function it_read_notifications_limit_to_a_given_number(NotificationDB $notificationRepo) - { - $to_id = 1; - $numbers = 5; - $order = 'asc'; - - $notificationRepo->readLimit($to_id,null,$numbers,$order)->shouldBeCalled() - ->willReturn($numbers); - - $this->readLimit($to_id,$numbers,$order)->shouldReturn($numbers); - } - - /** @test */ - function it_read_all_notification_of_the_given_entity(NotificationDB $notificationRepo) - { - $id = 1; - $entity = null; - $notificationDeleted = 10; - - $notificationRepo->readAll($id,$entity)->shouldBeCalled() - ->willReturn($notificationDeleted); - - $this->readAll($id)->shouldReturn($notificationDeleted); - } - - /** @test */ - function it_delete_a_notification_by_id(NotificationDB $notificationRepo) - { - $notification_id = 1; - - $notificationRepo->delete($notification_id)->shouldBeCalled() - ->willReturn(1); - - $this->delete($notification_id)->shouldReturn(1); - } - - /** @test */ - function it_delete_notification_limiting_the_number_of_the_given_entity(NotificationDB $notificationRepo) - { - $entity_id = 1; - $numberLimit = 5; - $order = 'asc'; - - $notificationRepo->deleteLimit($entity_id,null,$numberLimit,$order)->shouldBeCalled() - ->willReturn($numberLimit); - - $this->deleteLimit($entity_id,$numberLimit,$order)->shouldReturn($numberLimit); - } - - /** @test */ - function it_delete_all_notification_of_the_given_entity(NotificationDB $notificationRepo) - { - $entity_id = 1; - $notificationsDeleted = 10; - - $notificationRepo->deleteAll($entity_id,null)->shouldBeCalled() - ->willReturn($notificationsDeleted); - - $this->deleteAll($entity_id)->shouldReturn($notificationsDeleted); - } - - /** @test */ - function it_get_not_read_notification(NotificationDB $notificationRepo,NotifynderCollection $collection) - { - $entity_id = 1; - $limit = 10; - $paginate = null; - - $notificationRepo->getNotRead($entity_id,null,$limit,$paginate,'desc')->shouldBeCalled() - ->willReturn($collection); - - $collection->parse()->shouldBeCalled()->willReturn([]); - - $this->getNotRead($entity_id,$limit,$paginate,'desc')->shouldReturn([]); - } - - /** @test */ - function it_get_all_notifications_of_the_given_entity(NotificationDB $notificationRepo,NotifynderCollection $collection) - { - $entity_id = 1; - $limit = 10; - $paginate = null; - - $notificationRepo->getAll($entity_id,null,$limit,$paginate,'desc')->shouldBeCalled() - ->willReturn($collection); - - $collection->parse()->shouldBeCalled()->willReturn([]); - - $this->getAll($entity_id,$limit,$paginate)->shouldReturn([]); - } - - /** @test */ - function it_get_last_notification_of_the_current_entity(NotificationDB $notificationRepo) - { - $id = 1; - - $notificationRepo->getLastNotification($id,null)->shouldBeCalled()->willReturn(new Notification()); - - $this->getLastNotification($id)->shouldReturnAnInstanceOf(Notification::class); - } - - /** @test */ - function it_get_last_notification_of_the_current_entity_filtering_by_category(NotificationDB $notificationRepo) - { - $id = 1; - $category = 'notifynder.category'; - - $notificationRepo->getLastNotificationByCategory($category,$id,null)->shouldBeCalled()->willReturn(new Notification()); - - $this->getLastNotificationByCategory($category,$id)->shouldReturnAnInstanceOf(Notification::class); - } - - /** @test */ - function it_send_a_single_notification(NotificationDB $notificationRepo) - { - $notificationData = []; - $notification = new Notification(); - - $notificationRepo->storeSingle($notificationData)->shouldBeCalled() - ->willReturn($notification); - - $this->sendOne($notificationData)->shouldReturnAnInstanceOf(Notification::class); - } - - /** @test */ - function it_send_multiple_notification(NotificationDB $notificationRepo) - { - $notificationData = []; - $notificationsSent = 5; - - $notificationRepo->storeMultiple($notificationData)->shouldBeCalled() - ->willReturn($notificationsSent); - - $this->sendMultiple($notificationData)->shouldReturn($notificationsSent); - } - - /** @test */ - function it_count_notification_not_read(NotificationDB $notificationRepo) - { - $entity_id = 1; - $notificationCount = 10; - - $notificationRepo->countNotRead($entity_id,null)->shouldBeCalled() - ->willReturn($notificationCount); - - $this->countNotRead($entity_id)->shouldReturn($notificationCount); - } - - /** @test */ - function it_delete_notification_by_categories(NotificationDB $notificationRepo) - { - $categoryName = 'notifynder.test'; - - $notificationRepo->deleteByCategory($categoryName,false)->shouldBeCalled() - ->willReturn(1); - - $this->deleteByCategory($categoryName)->shouldReturn(1); - } -} diff --git a/spec/Fenos/Notifynder/Parsers/NotifynderParserSpec.php b/spec/Fenos/Notifynder/Parsers/NotifynderParserSpec.php deleted file mode 100755 index d641a5e..0000000 --- a/spec/Fenos/Notifynder/Parsers/NotifynderParserSpec.php +++ /dev/null @@ -1,63 +0,0 @@ -shouldHaveType('Fenos\Notifynder\Parsers\NotifynderParser'); - } - - /** @test */ - function it_should_replace_special_values_with_an_associative_array() - { - $extra = ['hello' => 'world']; - - $notification = [ - 'body' => [ - 'text' => 'Hi jhon hello {extra.hello}' - ], - 'extra' => json_encode($extra) - ]; - - $this->parse($notification)->shouldReturn('Hi jhon hello world'); - } - - /** @test */ - function it_replace_from_values_relations() - { - $notification = [ - 'body' => [ - 'text' => 'Hi {to.username} hello' - ], - 'to' => [ - 'username' => 'jhon', - ], - 'extra' => null - ]; - - $this->parse($notification)->shouldReturn('Hi jhon hello'); - } - - /** @test */ - function it_replace_both_in_a_string() - { - $extra = ['hello' => 'world']; - - $notification = [ - 'body' => [ - 'text' => 'Hi {to.username} hello {extra.hello}' - ], - 'to' => [ - 'username' => 'jhon', - ], - 'extra' => json_encode($extra) - ]; - - $this->parse($notification)->shouldReturn('Hi jhon hello world'); - } -} diff --git a/spec/Fenos/Notifynder/Senders/SendMultipleSpec.php b/spec/Fenos/Notifynder/Senders/SendMultipleSpec.php deleted file mode 100755 index b4ba957..0000000 --- a/spec/Fenos/Notifynder/Senders/SendMultipleSpec.php +++ /dev/null @@ -1,33 +0,0 @@ -beConstructedWith($notifications); - } - - function it_is_initializable() - { - $this->shouldHaveType('Fenos\Notifynder\Senders\SendMultiple'); - } - - /** @test */ - function it_send_multiple_notification(StoreNotification $storeNotification) - { - $multiple = [ - ]; - - $storeNotification->storeMultiple($multiple)->shouldBeCalled() - ->willReturn(1); - - $this->send($storeNotification)->shouldReturn(1); - } -} diff --git a/spec/Fenos/Notifynder/Senders/SendOneSpec.php b/spec/Fenos/Notifynder/Senders/SendOneSpec.php deleted file mode 100755 index f777dc3..0000000 --- a/spec/Fenos/Notifynder/Senders/SendOneSpec.php +++ /dev/null @@ -1,46 +0,0 @@ -beConstructedWith($infoNotification); - } - - function it_is_initializable() - { - $this->shouldHaveType('Fenos\Notifynder\Senders\SendOne'); - } - - /** @test */ - function it_send_a_single_notification_having_the_category_(StoreNotification $storeNotification) - { - $infoNotification = [ - 'category_id' => 1 - ]; - - $this->beConstructedWith($infoNotification); - - $storeNotification->storeSingle($infoNotification)->shouldBeCalled() - ->willReturn(new Notification()); - - $this->send($storeNotification)->shouldReturnAnInstanceOf(Notification::class); - } - - /** @test */ - function it_try_to_send_a_notification_without_category_id(StoreNotification $storeNotification) - { - // throw exception because I didn't specified a category_id - $this->shouldThrow(CategoryNotFoundException::class) - ->during('send',[$storeNotification]); - } -} diff --git a/spec/Fenos/Notifynder/Senders/SenderFactorySpec.php b/spec/Fenos/Notifynder/Senders/SenderFactorySpec.php deleted file mode 100755 index 6920c3b..0000000 --- a/spec/Fenos/Notifynder/Senders/SenderFactorySpec.php +++ /dev/null @@ -1,57 +0,0 @@ -beConstructedWith($notifynderGroup,$notifynderCategory); - } - - function it_is_initializable() - { - $this->shouldHaveType('Fenos\Notifynder\Senders\SenderFactory'); - } - - /** @test */ - function it_get_a_dynamic_sender_checking_array_type_GET_SINGLE() - { - // if the array is multidimensional then - // send multiple - $notification = []; - $category = 1; - - $this->getSender($notification,$category)->shouldReturnAnInstanceOf(SendOne::class); - } - - /** @test */ - function it_get_a_dynamic_sender_checking_array_type_GET_MULTIPLE() - { - // if the array is multidimensional then - // send multiple - $notification = [ - 0 => [] - ]; - $category = 1; - - $this->getSender($notification,$category)->shouldReturnAnInstanceOf(SendMultiple::class); - } - - /** @test */ - function it_get_the_send_group_sender() - { - $group_name = 'mygroup'; - $info = []; - - $this->sendGroup($group_name,$info)->shouldReturnAnInstanceOf(SendGroup::class); - } -} diff --git a/spec/Fenos/Notifynder/Senders/SenderManagerSpec.php b/spec/Fenos/Notifynder/Senders/SenderManagerSpec.php deleted file mode 100755 index 3c92ef5..0000000 --- a/spec/Fenos/Notifynder/Senders/SenderManagerSpec.php +++ /dev/null @@ -1,116 +0,0 @@ -beConstructedWith($senderFactory,$storeNotification,$application); - } - - function it_is_initializable() - { - $this->shouldHaveType('Fenos\Notifynder\Senders\SenderManager'); - } - - /** @test */ - function it_send_now_a_notification(SenderFactory $senderFactory, - DefaultSender $sender, - StoreNotification $storeNotification) - { - $notifications = []; - $category = 1; - - $senderFactory->getSender($notifications,$category)->shouldBeCalled() - ->willReturn($sender); - - $sender->send($storeNotification)->shouldBeCalled() - ->willReturn(1); - - $this->sendNow($notifications,$category)->shouldReturn(1); - } - - /** @test */ - function it_send_one_notification(SenderFactory $senderFactory, - DefaultSender $sender, - StoreNotification $storeNotification) - { - $notifications = []; - $category = 1; - - $senderFactory->sendSingle($notifications,$category)->shouldBeCalled() - ->willReturn($sender); - - $sender->send($storeNotification,$category)->shouldBeCalled() - ->willReturn(1); - - $this->sendOne($notifications,$category)->shouldReturn(1); - } - - /** @test */ - function it_send_multiple_notification(SenderFactory $senderFactory, - DefaultSender $sender, - StoreNotification $storeNotification) - { - $notifications = []; - - $senderFactory->sendMultiple($notifications)->shouldBeCalled() - ->willReturn($sender); - - $sender->send($storeNotification)->shouldBeCalled() - ->willReturn(1); - - $this->sendMultiple($notifications)->shouldReturn(1); - } - - /** @test */ - function it_call_an_extended_method(SenderFactory $senderFactory, - DefaultSender $sender, - StoreNotification $storeNotification) - { - $notifications = []; - - $this->extend('sendExtended', function($app) use ($sender){ - return new TestExtender(); - }); - - $this->sendExtended($notifications)->shouldReturn([]); - } - - /** @test */ - function it_try_to_call_an_inexistent_extended_method() - { - $this->shouldThrow(BadMethodCallException::class)->during('NotExistingExtender',[]); - } -} - -/* -|-------------------------------------------------------------------------- -| Extended class -|-------------------------------------------------------------------------- -| Test Extender sender class ---------------------------------------------------------------------------*/ - -class TestExtender implements DefaultSender -{ - - /** - * Send Single notification - * - * @param StoreNotification $sender - * @return mixed - */ - public function send(StoreNotification $sender) - { - return []; - } -} \ No newline at end of file diff --git a/spec/Fenos/Notifynder/Translator/TranslatorManagerSpec.php b/spec/Fenos/Notifynder/Translator/TranslatorManagerSpec.php deleted file mode 100755 index 3de3a62..0000000 --- a/spec/Fenos/Notifynder/Translator/TranslatorManagerSpec.php +++ /dev/null @@ -1,130 +0,0 @@ -beConstructedWith($compiler,$config); - } - - function it_is_initializable() - { - $this->shouldHaveType('Fenos\Notifynder\Translator\TranslatorManager'); - } - - /** @test */ - function it_translate_the_given_category_in_the_given_language(Compiler $compiler, Repository $config) - { - $filePath = 'cached/file'; - $categoryToTranslate = 'categoryName'; - $translations = [ - 'it' => [ - $categoryToTranslate => 'translation' - ] - ]; - - $compiler->getFilePath()->shouldBeCalled() - ->willReturn($filePath); - - $config->get('notifynder.translations')->shouldBeCalled() - ->willReturn($translations); - - $compiler->cacheFile($translations)->shouldBeCalled(); - - - $this->translate('it', $categoryToTranslate) - ->shouldReturn($translations['it'][$categoryToTranslate]); - } - - /** @test */ - function it__try_to_translate_the_given_category(Compiler $compiler, Repository $config) - { - $filePath = 'cached/file'; - $categoryToTranslate = 'categoryName'; - $translations = [ - 'it' => [ - $categoryToTranslate => 'translation' - ] - ]; - - $compiler->getFilePath()->shouldBeCalled() - ->willReturn($filePath); - - $config->get('notifynder.translations')->shouldBeCalled() - ->willReturn($translations); - - $compiler->cacheFile($translations)->shouldBeCalled(); - - $this->shouldThrow(NotificationTranslationNotFoundException::class) - ->during('translate',['it','not existing']); - } - - /** @test */ - function it_get_a_language_from_the_translations(Compiler $compiler, Repository $config) - { - $filePath = 'cached/file'; - $translations = [ - 'it' => [ - 'categoryName' => 'translation' - ] - ]; - - $compiler->getFilePath()->shouldBeCalled() - ->willReturn($filePath); - - $config->get('notifynder.translations')->shouldBeCalled() - ->willReturn($translations); - - $compiler->cacheFile($translations)->shouldBeCalled(); - - $this->getLanguage('it')->shouldReturn($translations['it']); - } - - /** @test */ - function it__try_to_get_a_language_from_the_translations(Compiler $compiler, Repository $config) - { - $filePath = 'cached/file'; - $translations = [ - 'it' => [ - 'categoryName' => 'translation' - ] - ]; - - $compiler->getFilePath()->shouldBeCalled() - ->willReturn($filePath); - - $config->get('notifynder.translations')->shouldBeCalled() - ->willReturn($translations); - - $compiler->cacheFile($translations)->shouldBeCalled(); - - $this->shouldThrow(NotificationLanguageNotFoundException::class) - ->during('getLanguage',['en']); - } - - /** @test */ - function it_get_the_translations_from_never_cached_config_file(Compiler $compiler, Repository $config) - { - $filePath = 'cached/file'; - $translations = []; - - $compiler->getFilePath()->shouldBeCalled() - ->willReturn($filePath); - - $config->get('notifynder.translations')->shouldBeCalled() - ->willReturn($translations); - - $compiler->cacheFile($translations)->shouldBeCalled(); - - $this->getTranslations()->shouldReturn($translations); - } -} diff --git a/src/Notifynder/Artisan/CreateCategory.php b/src/Notifynder/Artisan/CreateCategory.php deleted file mode 100755 index 1639f0f..0000000 --- a/src/Notifynder/Artisan/CreateCategory.php +++ /dev/null @@ -1,73 +0,0 @@ -notifynderCategory = $notifynderCategory; - } - - /** - * Execute the console command. - * - * @return mixed - */ - public function fire() - { - $name = $this->argument('name'); - $text = $this->argument('text'); - - $createCategory = $this->notifynderCategory->add($name, $text); - - if ($createCategory) { - $this->info("Category $createCategory->name has been created"); - } else { - $this->error('The category has been not created'); - } - } - - /** - * Get the console command arguments. - * - * @return array - */ - protected function getArguments() - { - return array( - array('name', InputArgument::REQUIRED, 'Name of the category.'), - array('text', InputArgument::REQUIRED, 'Text of the category.'), - ); - } -} diff --git a/src/Notifynder/Artisan/CreateGroup.php b/src/Notifynder/Artisan/CreateGroup.php deleted file mode 100755 index c5a3551..0000000 --- a/src/Notifynder/Artisan/CreateGroup.php +++ /dev/null @@ -1,68 +0,0 @@ -notifynderGroup = $notifynderGroup; - } - - /** - * Execute the console command. - * - * @return mixed - */ - public function fire() - { - $nameGroup = $this->argument('name'); - - if ($this->notifynderGroup->addGroup($nameGroup)) { - $this->info("Group {$nameGroup} has Been created"); - } else { - $this->error('The name must be a string with dots as namespaces'); - } - } - - /** - * Get the console command arguments. - * - * @return array - */ - protected function getArguments() - { - return array( - array('name', InputArgument::REQUIRED, 'user.post.add'), - ); - } -} diff --git a/src/Notifynder/Artisan/DeleteCategory.php b/src/Notifynder/Artisan/DeleteCategory.php deleted file mode 100755 index 94e8256..0000000 --- a/src/Notifynder/Artisan/DeleteCategory.php +++ /dev/null @@ -1,79 +0,0 @@ -notifynderCategory = $notifynderCategory; - } - - /** - * Execute the console command. - * - * @return mixed - */ - public function fire() - { - $indentifier = $this->argument('identifier'); - - if ($this->isIntegerValue($indentifier)) { - $delete = $this->notifynderCategory->delete($indentifier); - } else { - $delete = $this->notifynderCategory->deleteByName($indentifier); - } - - if ($delete) { - $this->info('Category has been deleted'); - } else { - $this->error('Category Not found'); - } - } - - public function isIntegerValue($indentifier) - { - return preg_match('/[0-9]/', $indentifier); - } - - /** - * Get the console command arguments. - * - * @return array - */ - protected function getArguments() - { - return array( - array('identifier', InputArgument::REQUIRED, '1 - nameCategory'), - ); - } -} diff --git a/src/Notifynder/Artisan/PushCategoryToGroup.php b/src/Notifynder/Artisan/PushCategoryToGroup.php deleted file mode 100755 index 1d94802..0000000 --- a/src/Notifynder/Artisan/PushCategoryToGroup.php +++ /dev/null @@ -1,111 +0,0 @@ -notifynderGroup = $notifynderGroup; - $this->artisanOptionsParser = $artisanOptionsParser; - } - - /** - * Execute the console command. - * - * @return mixed - */ - public function fire() - { - $arguments = $this->getArgumentsConsole(); - - $groupCategories = $this->notifynderGroup - ->addMultipleCategoriesToGroup($arguments); - - if ($groupCategories) { - foreach ($groupCategories->categories as $category) { - $this->info("Category {$category->name} has been associated to the group {$groupCategories->name}"); - } - } else { - $this->error('The name must be a string with dots as namespaces'); - } - } - - /** - * @return array|string - */ - public function getArgumentsConsole() - { - $names = $this->argument('name'); - - $categories = $this->option('categories'); - - $categories = $this->artisanOptionsParser->parse($categories); - - array_unshift($categories, $names); - - return $categories; - } - - /** - * Get the console command arguments. - * - * @return array - */ - protected function getArguments() - { - return array( - array('name', InputArgument::REQUIRED, 'user.post.add'), - ); - } - - /** - * Get the console command options. - * - * @return array - */ - protected function getOptions() - { - return array( - array('categories', null, InputOption::VALUE_OPTIONAL, 'notifynder.name', []), - ); - } -} diff --git a/src/Notifynder/Builder/Builder.php b/src/Notifynder/Builder/Builder.php new file mode 100755 index 0000000..5a6ee15 --- /dev/null +++ b/src/Notifynder/Builder/Builder.php @@ -0,0 +1,313 @@ +notification = new Notification(); + } + + /** + * Set the category for this notification. + * + * @param string|int|\Fenos\Notifynder\Models\NotificationCategory $category + * @return $this + */ + public function category($category) + { + $categoryId = NotificationCategory::getIdByCategory($category); + $this->setNotificationData('category_id', $categoryId); + + return $this; + } + + /** + * Set the sender for this notification. + * + * @return $this + */ + public function from() + { + $args = func_get_args(); + $this->setEntityData($args, 'from'); + + return $this; + } + + /** + * Set the sender anonymous for this notification. + * + * @return $this + */ + public function anonymous() + { + $this->setNotificationData('from_type', null); + $this->setNotificationData('from_id', null); + + return $this; + } + + /** + * Set the receiver for this notification. + * + * @return $this + */ + public function to() + { + $args = func_get_args(); + $this->setEntityData($args, 'to'); + + return $this; + } + + /** + * Set the url for this notification. + * + * @param string $url + * @return $this + */ + public function url($url) + { + TypeChecker::isString($url); + $this->setNotificationData('url', $url); + + return $this; + } + + /** + * Set the expire date for this notification. + * + * @param Carbon|\DateTime $datetime + * @return $this + */ + public function expire(Carbon $datetime) + { + TypeChecker::isDate($datetime); + $carbon = new Carbon($datetime); + $this->setNotificationData('expires_at', $carbon); + + return $this; + } + + /** + * Set the extra values for this notification. + * You can extend the existing extras or override them - important for multiple calls of extra() on one notification. + * + * @param array $extra + * @param bool $override + * @return $this + */ + public function extra(array $extra = [], $override = true) + { + TypeChecker::isArray($extra); + if (! $override) { + $extra = array_merge($this->getNotificationData('extra', []), $extra); + } + $this->setNotificationData('extra', $extra); + + return $this; + } + + /** + * Set updated_at and created_at fields. + */ + public function setDates() + { + $date = Carbon::now(); + + $this->setNotificationData('updated_at', $date); + $this->setNotificationData('created_at', $date); + } + + /** + * Set a single field value. + * + * @param string $key + * @param mixed $value + * @return $this + */ + public function setField($key, $value) + { + $additionalFields = notifynder_config()->getAdditionalFields(); + if (in_array($key, $additionalFields)) { + $this->setNotificationData($key, $value); + } + + return $this; + } + + /** + * Set polymorphic model values. + * + * @param array $entity + * @param string $property + */ + protected function setEntityData($entity, $property) + { + if (is_array($entity) && count($entity) == 2) { + TypeChecker::isString($entity[0]); + TypeChecker::isNumeric($entity[1]); + + $type = $entity[0]; + $id = $entity[1]; + } elseif ($entity[0] instanceof Model) { + $type = $entity[0]->getMorphClass(); + $id = $entity[0]->getKey(); + } else { + TypeChecker::isNumeric($entity[0]); + + $type = notifynder_config()->getNotifiedModel(); + $id = $entity[0]; + } + + $this->setNotificationData("{$property}_type", $type); + $this->setNotificationData("{$property}_id", $id); + } + + /** + * Get a single value of this notification. + * + * @param string $key + * @param null|mixed $default + * @return mixed + */ + protected function getNotificationData($key, $default = null) + { + return $this->notification->get($key, $default); + } + + /** + * Set a single value of this notification. + * + * @param string $key + * @param mixed $value + */ + protected function setNotificationData($key, $value) + { + $this->notification->set($key, $value); + } + + /** + * Get the current notification. + * + * @return Notification + * @throws UnvalidNotificationException + */ + public function getNotification() + { + if (! $this->notification->isValid()) { + throw new UnvalidNotificationException($this->notification); + } + + $this->setDates(); + + return $this->notification; + } + + /** + * Add a notification to the notifications array. + * + * @param Notification $notification + */ + public function addNotification(Notification $notification) + { + $this->notifications[] = $notification; + } + + /** + * Get all notifications. + * + * @return array + * @throws UnvalidNotificationException + */ + public function getNotifications() + { + if (count($this->notifications) == 0) { + $this->addNotification($this->getNotification()); + } + + return $this->notifications; + } + + /** + * Loop over data and call the callback with a new Builder instance and the key and value of the iterated data. + * + * @param array|\Traversable $data + * @param Closure $callback + * @return $this + * @throws UnvalidNotificationException + */ + public function loop($data, Closure $callback) + { + TypeChecker::isIterable($data); + + foreach ($data as $key => $value) { + $builder = new static(); + $callback($builder, $value, $key); + $this->addNotification($builder->getNotification()); + } + + return $this; + } + + /** + * @param string $offset + * @return bool + */ + public function offsetExists($offset) + { + return $this->notification->offsetExists($offset); + } + + /** + * @param string $offset + * @return mixed + */ + public function offsetGet($offset) + { + return $this->notification->offsetGet($offset); + } + + /** + * @param string $offset + * @param mixed $value + */ + public function offsetSet($offset, $value) + { + $this->notification->offsetSet($offset, $value); + } + + /** + * @param string $offset + */ + public function offsetUnset($offset) + { + $this->notification->offsetUnset($offset); + } +} diff --git a/src/Notifynder/Builder/BuilderRules.php b/src/Notifynder/Builder/BuilderRules.php deleted file mode 100755 index 1a01b03..0000000 --- a/src/Notifynder/Builder/BuilderRules.php +++ /dev/null @@ -1,142 +0,0 @@ -requiredFields as $field) { - if (! array_key_exists($field, $array)) { - return false; - } - } - - return true; - } - - /** - * Check if is a required field - * - * @param $offset - * @return bool - */ - public function isRequiredField($offset) - { - return (in_array($offset,$this->requiredFields)); - } - - /** - * Check if the array passed is - * multidimensional - * - * @param $arr - * @return bool - */ - protected function isReadyArrToFormatInJson(array $arr) - { - if ($this->isAssociativeArr($arr)) { - return true; - } - - if (count($arr) > 0) { - $error = "The 'extra' value must to be an associative array"; - throw new InvalidArgumentException($error); - } - - return false; - } - - /** - * @param array $arr - * @return bool - */ - protected function isAssociativeArr(array $arr) - { - return array_keys($arr) !== range(0, count($arr) - 1); - } - - /** - * Check if the array is - * multidimensional - * - * @param $arr - * @return bool - */ - public function isMultidimensionalArray($arr) - { - $rv = array_filter($arr, 'is_array'); - if (count($rv) > 0) { - return true; - } - - return false; - } -} diff --git a/src/Notifynder/Builder/Notification.php b/src/Notifynder/Builder/Notification.php new file mode 100644 index 0000000..f790911 --- /dev/null +++ b/src/Notifynder/Builder/Notification.php @@ -0,0 +1,222 @@ +getAdditionalRequiredFields(); + $this->requiredFields = array_merge($this->requiredFields, $customRequired); + } + + /** + * @return array + */ + public function attributes() + { + return $this->attributes; + } + + /** + * @param string $key + * @param null|mixed $default + * @return mixed + */ + public function attribute($key, $default = null) + { + return $this->get($key, $default); + } + + /** + * @param string $key + * @return bool + */ + public function has($key) + { + return Arr::has($this->attributes, $key); + } + + /** + * @param string $key + * @param null|mixed $default + * @return mixed + */ + public function get($key, $default = null) + { + return Arr::get($this->attributes, $key, $default); + } + + /** + * @param string $key + * @param mixed $value + */ + public function set($key, $value) + { + Arr::set($this->attributes, $key, $value); + } + + /** + * @return bool + */ + public function isValid() + { + foreach ($this->requiredFields as $field) { + if (! $this->has($field)) { + return false; + } + } + + return true; + } + + /** + * @param string $key + * @return mixed + */ + public function __get($key) + { + return $this->get($key); + } + + /** + * @param string $key + * @param mixed $value + */ + public function __set($key, $value) + { + $this->set($key, $value); + } + + /** + * @param int $options + * @return string + */ + public function toJson($options = 0) + { + return json_encode($this->jsonSerialize(), $options); + } + + /** + * @return array + */ + public function jsonSerialize() + { + return $this->toArray(); + } + + /** + * @return array + */ + public function toArray() + { + return array_map(function ($value) { + return $value instanceof Arrayable ? $value->toArray() : $value; + }, $this->attributes()); + } + + /** + * @return array + */ + public function toDbArray() + { + $notification = $this->toArray(); + if (array_key_exists('extra', $notification) && is_array($notification['extra'])) { + $notification['extra'] = json_encode($notification['extra']); + } + + return $notification; + } + + /** + * @return string + */ + public function getText() + { + if ($this->isValid()) { + $notification = new ModelNotification($this); + $notifynderParse = new NotificationParser(); + + return $notifynderParse->parse($notification, $this->category_id); + } + } + + /** + * @return string + */ + public function toString() + { + return $this->toJson(); + } + + /** + * @return string + */ + public function __toString() + { + return $this->toString(); + } + + /** + * @param string $offset + * @return bool + */ + public function offsetExists($offset) + { + return $this->has($offset); + } + + /** + * @param string $offset + * @return mixed + */ + public function offsetGet($offset) + { + return $this->get($offset); + } + + /** + * @param string $offset + * @param mixed $value + */ + public function offsetSet($offset, $value) + { + $this->set($offset, $value); + } + + /** + * @param string $offset + */ + public function offsetUnset($offset) + { + Arr::forget($this->attributes, $offset); + } +} diff --git a/src/Notifynder/Builder/NotifynderBuilder.php b/src/Notifynder/Builder/NotifynderBuilder.php deleted file mode 100755 index 164fd5a..0000000 --- a/src/Notifynder/Builder/NotifynderBuilder.php +++ /dev/null @@ -1,356 +0,0 @@ -notifynderCategory = $notifynderCategory; - } - - /** - * Set who will send the notification - * - * @return $this - */ - public function from() - { - $from = func_get_args(); - - $this->setEntityAction($from, 'from'); - - return $this; - } - - /** - * Set who will receive the notification - * - * @return $this - */ - public function to() - { - $from = func_get_args(); - - $this->setEntityAction($from, 'to'); - - return $this; - } - - /** - * Set the url of the notification - * - * @param $url - * @return $this - */ - public function url($url) - { - $this->isString($url); - - $this->setBuilderData('url', $url); - - return $this; - } - - /** - * Set expire time - * - * @param $datetime - * @return $this - */ - public function expire($datetime) - { - $this->isCarbon($datetime); - $this->setBuilderData('expire_time', $datetime); - - return $this; - } - - /** - * Set Category and covert it, to the id - * if name of it given - * - * @param $category - * @return $this - */ - public function category($category) - { - if (!is_numeric($category)) { - $category = $this->notifynderCategory - ->findByName($category)->id; - } - - $this->setBuilderData('category_id', $category); - - return $this; - } - - /** - * Set extra value - * - * @param $extra - * @return $this - */ - public function extra(array $extra = []) - { - $this->isReadyArrToFormatInJson($extra); - - $jsonExtraValues = json_encode($extra); - - $this->setBuilderData('extra', $jsonExtraValues); - - return $this; - } - - /** - * Build the array with the builder inside - * a Closure, it has more flexibility for - * the generation of your array - * - * - * @param callable|Closure $closure - * @return array|false - * @throws NotificationBuilderException - */ - public function raw(Closure $closure) - { - $builder = $closure($this); - - if (! is_null($builder)) { - return $this->toArray(); - } - - return false; - } - - /** - * Loop the datas for create - * multi notifications array - * - * @param $dataToIterate - * @param Closure $builder - * @return $this - * @throws NotificationBuilderException - */ - public function loop($dataToIterate, Closure $builder) - { - if ($this->isIterable($dataToIterate)) { - $notifications = []; - - $newBuilder = new self($this->notifynderCategory); - - foreach ($dataToIterate as $key => $data) { - $builder($newBuilder, $data, $key); - $notifications[] = $newBuilder->toArray(); - } - - $this->notifications = $notifications; - return $this; - } - - $error = "The data passed must be itarable"; - throw new InvalidArgumentException($error); - } - - /** - * Compose the builder to - * the array - * - * @throws NotificationBuilderException - * @return mixed - */ - public function toArray() - { - $hasMultipleNotifications = $this->isMultidimensionalArray($this->notifications); - - // If the builder is handling a single notification - // we will validate only it - if (! $hasMultipleNotifications) { - - $this->setDate(); - - if ($this->hasRequiredFields($this->notifications)) { - return $this->notifications; - } - } - - // If has multiple Notifications - // we will validate one by one - if ($hasMultipleNotifications) { - - $allow = []; - - foreach($this->notifications as $index => $notification) { - $allow[$index] = $this->hasRequiredFields($notification); - } - - if (! in_array(false,$allow)) { - return $this->notifications; - } - } - - $error = "The fields: 'from_id' , 'to_id', 'url', 'category_id' are required"; - throw new NotificationBuilderException($error); - } - - /** - * @param $var - * @return bool - */ - protected function isIterable($var) - { - return (is_array($var) || $var instanceof Traversable); - } - - /** - * It set the entity who will do - * the action of receive or - * send - * - * @param $from - * @param $property - * @return array - */ - protected function setEntityAction($from, $property) - { - // Check if has the entity as parameter - // it should be the firstOne - if ($this->hasEntity($from)) { - $this->isString($from[0]); - $this->isNumeric($from[1]); - - $this->setBuilderData("{$property}_type", $from[0]); - $this->setBuilderData("{$property}_id", $from[1]); - } else { - $this->isNumeric($from[0]); - $this->setBuilderData("{$property}_id", $from[0]); - } - } - - /** - * If the values passed are 2 or more, - * it means that you spefied the entity - * over then the id - * - * @param array $info - * @return bool - */ - protected function hasEntity(array $info) - { - return count($info) >= 2; - } - - /** - * Set date on the array - */ - protected function setDate() - { - $this->date = $data = Carbon::now(); - - $this->setBuilderData('updated_at', $data); - $this->setBuilderData('created_at', $data); - } - - /** - * @return string - */ - protected function getDate() - { - return $this->date; - } - - /** - * Set builder Data - * - * @param $field - * @param $data - */ - protected function setBuilderData($field, $data) - { - return $this->notifications[$field] = $data; - } - - - /** - * @param mixed $offset - * @return bool - */ - public function offsetExists($offset) - { - return array_key_exists($offset,$this->notifications); - } - - - /** - * @param mixed $offset - * @return mixed - */ - public function offsetGet($offset) - { - return $this->notifications[$offset]; - } - - - /** - * @param mixed $offset - * @param mixed $value - */ - public function offsetSet($offset, $value) - { - if (method_exists($this, $offset)) { - - return $this->{$offset}($value); - } - - if ($this->isRequiredField($offset)) { - $this->notifications[$offset] = $value; - } - } - - - /** - * @param mixed $offset - * @return null - */ - public function offsetUnset($offset) - { - unset($this->notifications[$offset]); -}} diff --git a/src/Notifynder/Categories/CategoryManager.php b/src/Notifynder/Categories/CategoryManager.php deleted file mode 100755 index a949f83..0000000 --- a/src/Notifynder/Categories/CategoryManager.php +++ /dev/null @@ -1,134 +0,0 @@ -categoryRepo = $categoryRepo; - } - - /** - * Find a category by name - * - * @param $name - * @throws CategoryNotFoundException - * @return mixed - */ - public function findByName($name) - { - $category = $this->categoryRepo->findByName($name); - - if (is_null($category)) { - $error = "Category Not Found"; - throw new CategoryNotFoundException($error); - } - - return $category; - } - - /** - * Find categories by names, - * pass the name as an array - * - * @param $name - * @throws CategoryNotFoundException - * @return mixed - */ - public function findByNames(array $name) - { - $category = $this->categoryRepo->findByNames($name); - - if (count($category) == 0) { - $error = "Category Not Found"; - throw new CategoryNotFoundException($error); - } - - return $category; - } - - /** - * Find a category by id - * - * @param $id - * @throws CategoryNotFoundException - * @return mixed - */ - public function find($id) - { - $category = $this->categoryRepo->find($id); - - if (is_null($category)) { - $error = "Category Not Found"; - throw new CategoryNotFoundException($error); - } - - return $category; - } - - /** - * Add a category to the DB - * - * @param array $name - * @param $text - * @return \Fenos\Notifynder\Models\NotificationCategory - */ - public function add($name, $text) - { - return $this->categoryRepo->add($name, $text); - } - - /** - * Delete category by ID - * - * @param $id - * @return mixed - */ - public function delete($id) - { - return $this->categoryRepo->delete($id); - } - - /** - * Delete category by name - * - * @param $name - * @return mixed - */ - public function deleteByName($name) - { - return $this->categoryRepo->deleteByName($name); - } - - /** - * Update a category - * - * @param array $data - * @param $id - * @return mixed - */ - public function update(array $data, $id) - { - return $this->categoryRepo->update($data, $id); - } -} diff --git a/src/Notifynder/Categories/CategoryRepository.php b/src/Notifynder/Categories/CategoryRepository.php deleted file mode 100755 index 1bb4462..0000000 --- a/src/Notifynder/Categories/CategoryRepository.php +++ /dev/null @@ -1,115 +0,0 @@ -categoryModel = $categoryModel; - } - - /** - * Find By Id - * - * @param $id - * @return mixed - */ - public function find($id) - { - return $this->categoryModel->find($id); - } - - /** - * Find by name - * - * @param $name - * @return mixed - */ - public function findByName($name) - { - return $this->categoryModel->where('name', $name) - ->first(); - } - - /** - * Find by names returnig - * lists of ids - * - * @param $name - * @return mixed - */ - public function findByNames(array $name) - { - return $this->categoryModel->whereIn('name', $name) - ->get(); - } - - /** - * Add a category to the DB - * - * @param array $name - * @param $text - * @return static - */ - public function add($name, $text) - { - return $this->categoryModel->create(compact('name', 'text')); - } - - /** - * Delete category by ID - * - * @param $id - * @return mixed - */ - public function delete($id) - { - return $this->categoryModel->where('id', $id) - ->delete(); - } - - /** - * Delete category by name - * - * @param $name - * @return mixed - */ - public function deleteByName($name) - { - return $this->categoryModel->where('name', $name) - ->delete(); - } - - /** - * Update a category by id - * - * @param array $data - * @param $id - * @return mixed - */ - public function update(array $data, $id) - { - return $this->categoryModel->where('id', $id) - ->update($data); - } -} diff --git a/src/Notifynder/Collections/Config.php b/src/Notifynder/Collections/Config.php new file mode 100644 index 0000000..1371033 --- /dev/null +++ b/src/Notifynder/Collections/Config.php @@ -0,0 +1,153 @@ +reload(); + } + + /** + * @return bool + */ + public function isPolymorphic() + { + return (bool) $this->get('polymorphic'); + } + + /** + * @return bool + */ + public function isStrict() + { + return (bool) $this->get('strict_extra'); + } + + /** + * @return bool + */ + public function isTranslated() + { + return (bool) $this->get('translation.enabled'); + } + + /** + * @return string + */ + public function getNotificationModel() + { + $class = $this->get('notification_model'); + if (class_exists($class)) { + return $class; + } + + return Notification::class; + } + + /** + * @return string + * @throws InvalidArgumentException + */ + public function getNotifiedModel() + { + $class = $this->get('model'); + if (class_exists($class)) { + return $class; + } + throw new InvalidArgumentException("The model class [{$class}] doesn't exist."); + } + + /** + * @return array + */ + public function getAdditionalFields() + { + return Arr::flatten($this->get('additional_fields', [])); + } + + /** + * @return array + */ + public function getAdditionalRequiredFields() + { + return Arr::flatten($this->get('additional_fields.required', [])); + } + + /** + * @return string + */ + public function getTranslationDomain() + { + return $this->get('translation.domain', 'notifynder'); + } + + /** + * @param string $key + * @param null|mixed $default + * @return mixed + */ + public function get($key, $default = null) + { + return Arr::get($this->items, $key, $default); + } + + /** + * @param string $key + * @return bool + */ + public function has($key) + { + return Arr::has($this->items, $key); + } + + /** + * @param string $key + * @param null $value + */ + public function set($key, $value = null) + { + Arr::set($this->items, $key, $value); + app('config')->set('notifynder.'.$key, $value); + } + + public function reload() + { + $this->items = app('config')->get('notifynder'); + } + + /** + * @param string $key + * @return mixed + */ + public function __get($key) + { + return $this->get($key); + } + + /** + * @param string $key + * @param mixed $value + */ + public function __set($key, $value) + { + $this->set($key, $value); + } +} diff --git a/src/Notifynder/Contracts/CategoryDB.php b/src/Notifynder/Contracts/CategoryDB.php deleted file mode 100755 index 4d0f9f3..0000000 --- a/src/Notifynder/Contracts/CategoryDB.php +++ /dev/null @@ -1,72 +0,0 @@ - [ - * 'name.category' => 'text to translate' - * ] - * ] - * - * @package Fenos\Notifynder\Translator - */ -interface NotifynderTranslator -{ - - /** - * Translate the given category - * - * @param $language - * @param $nameCategory - * @return mixed - * @throws NotificationLanguageNotFoundException - * @throws NotificationTranslationNotFoundException - */ - public function translate($language, $nameCategory); - - /** - * Get selected language of tranlsations - * - * @param $language - * @return mixed - * @throws NotificationLanguageNotFoundException - */ - public function getLanguage($language); - - /** - * Get translations - * - * @return array|mixed - */ - public function getTranslations(); -} diff --git a/src/Notifynder/Contracts/Sender.php b/src/Notifynder/Contracts/Sender.php deleted file mode 100755 index 3088526..0000000 --- a/src/Notifynder/Contracts/Sender.php +++ /dev/null @@ -1,17 +0,0 @@ -notification = $notification; + } + + /** + * @return Notification + */ + public function getNotification() + { + return $this->notification; + } +} diff --git a/src/Notifynder/Facades/Notifynder.php b/src/Notifynder/Facades/Notifynder.php old mode 100755 new mode 100644 index 5f3ff0f..fae558f --- a/src/Notifynder/Facades/Notifynder.php +++ b/src/Notifynder/Facades/Notifynder.php @@ -1,13 +1,15 @@ -notificationCategory = $notificationCategory; - $this->notificationGropup = $notificationGropup; - } - - /** - * Add a category in a group - * - * @param $group_id - * @param $category_id - * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|static - */ - public function addCategoryToGroupById($group_id, $category_id) - { - $group = $this->notificationGropup->find($group_id); - $group->categories()->attach($category_id); - - return $group; - } - - /** - * Add a category in a group - * by names given - * - * @param $group_name - * @param $category_name - * @return mixed - */ - public function addCategoryToGroupByName($group_name, $category_name) - { - $group = $this->notificationGropup->where('name', $group_name)->first(); - - $category = $this->notificationCategory->findByName($category_name); - - $group->categories()->attach($category->id); - - return $group; - } - - /** - * Add multiple categories by them names - * to a group - * - * @param $group_name - * @param $names - * @return mixed - */ - public function addMultipleCategoriesToGroup($group_name, array $names) - { - $group = $this->notificationGropup->where('name', $group_name)->first(); - - $categories = $this->notificationCategory->findByNames($names); - - foreach ($categories as $category) { - $group->categories()->attach($category->id); - } - - return $group; - } -} diff --git a/src/Notifynder/Groups/GroupManager.php b/src/Notifynder/Groups/GroupManager.php deleted file mode 100755 index 5acaccc..0000000 --- a/src/Notifynder/Groups/GroupManager.php +++ /dev/null @@ -1,150 +0,0 @@ -groupRepo = $groupRepo; - $this->groupCategory = $groupCategory; - } - - /** - * Find a group by id - * - * @param $group_id - * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|static - * @throws \Fenos\Notifynder\Exceptions\NotifynderGroupNotFoundException - */ - public function findById($group_id) - { - $group = $this->groupRepo->find($group_id); - - if (is_null($group)) { - $error = "Group Not Found"; - throw new NotifynderGroupNotFoundException($error); - } - - return $group; - } - - /** - * Find a group By name - * - * @param $group_name - * @return mixed - * @throws \Fenos\Notifynder\Exceptions\NotifynderGroupNotFoundException - */ - public function findByName($group_name) - { - $group = $this->groupRepo->findByName($group_name); - - if (is_null($group)) { - $error = "Group Not Found"; - throw new NotifynderGroupNotFoundException($error); - } - - return $group; - } - - /** - * Add category to a group - * giving the ids of them - * - * @param $gorup_id - * @param $category_id - * @return mixed - */ - public function addCategoryToGroupById($gorup_id, $category_id) - { - return $this->groupCategory->addCategoryToGroupById($gorup_id, $category_id); - } - - /** - * Add category to a group - * giving the ids of them - * - * @param $gorup_name - * @param $category_name - * @return mixed - */ - public function addCategoryToGroupByName($gorup_name, $category_name) - { - return $this->groupCategory->addCategoryToGroupByName($gorup_name, $category_name); - } - - /** - * Add Multiple categories in a group - * First parameter is the group name - * all the rest are categories - * - * @return mixed - */ - public function addMultipleCategoriesToGroup() - { - $names = func_get_args(); - - $names = (is_array($names[0])) ? $names[0] : $names; - - // First parameter is the group name - $group_name = array_shift($names); - - $names = (is_array($names[1])) ? $names[1] : $names; - - return $this->groupCategory->addMultipleCategoriesToGroup($group_name, $names); - } - - /** - * Add a group in the db - * - * @param $name - * @throws InvalidArgumentException - * @return \Illuminate\Database\Eloquent\Model|static - */ - public function addGroup($name) - { - if ($this->isStringWithDots($name)) { - return $this->groupRepo->create($name); - } - - $error = "The name must be a string with dots as namespaces"; - throw new InvalidArgumentException($error); - } - - /** - * Check if a string with dots - * - * @param $name - * @return bool - */ - protected function isStringWithDots($name) - { - return strpos($name, '.'); - } -} diff --git a/src/Notifynder/Groups/GroupRepository.php b/src/Notifynder/Groups/GroupRepository.php deleted file mode 100755 index 7ae9bbf..0000000 --- a/src/Notifynder/Groups/GroupRepository.php +++ /dev/null @@ -1,71 +0,0 @@ -groupModel = $groupModel; - } - - /** - * Find a group by ID - * - * @param $group_id - * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|static - */ - public function find($group_id) - { - return $this->groupModel->find($group_id); - } - - /** - * Find a group by name - * - * @param $name - * @return mixed - */ - public function findByName($name) - { - return $this->groupModel->where('name', $name)->first(); - } - - /** - * Create a new group - * - * @param $name - * @return \Illuminate\Database\Eloquent\Model - */ - public function create($name) - { - return $this->groupModel->create(compact('name')); - } - - /** - * Delete a group - * - * @param $group_id - * @return mixed - */ - public function delete($group_id) - { - return $this->groupModel->where('id', $group_id)->delete(); - } -} diff --git a/src/Notifynder/Handler/Dispatcher.php b/src/Notifynder/Handler/Dispatcher.php deleted file mode 100755 index 3a4b04e..0000000 --- a/src/Notifynder/Handler/Dispatcher.php +++ /dev/null @@ -1,152 +0,0 @@ -event = $event; - } - - /** - * It fire the event associated to the passed key, - * trigging the listener method bound with - * - * @param Notifynder $notifynder - * @param string $eventName - * @param string $category_name - * @param mixed|null $values - * @return mixed|null - */ - public function fire(Notifynder $notifynder, $eventName, $category_name = null, $values = []) - { - // Generete the event from the name given - $eventName = $this->generateEventName($eventName); - - // Instantiate the Notifynder event Object that will provide - // nice way to get your data on the handler. It will be the first - // parameter - $event = new NotifynderEvent($eventName, $category_name, $values); - - // Fire the event given expecting an array of notifications or falsy - // value to not send the notification - $notificationsResult = $this->event->fire($eventName, [$event, $notifynder]); - - // if the event return an array of notifications then it will - // send automatically - if ($this->hasNotificationToSend($notificationsResult)) { - - // Send the notification with the sender - // method specified in the property - return call_user_func_array( - [$notifynder,$this->sender], - [$notificationsResult[0]] - ); - } - - return null; - } - - /** - * Deletegate events to categories - * - * @param Notifynder $notifynder - * @param array $data - * @param array $events - * @return mixed - */ - public function delegate(Notifynder $notifynder, $data = [], array $events) - { - foreach ($events as $category => $event) { - $this->fire($notifynder, $event, $category, $data); - } - } - - /** - * Tell the disptacher to send - * the notification with a custom - * (extended method) - * - * @param $customMethod - * @return $this - */ - public function sendWith($customMethod) - { - $this->sender = $customMethod; - - return $this; - } - - /** - * Boot The listeners - * - * @param array $listeners - */ - public function boot(array $listeners) - { - if (count($listeners) > 0) { - foreach ($listeners as $key => $listener) { - // Notifynder.name.* - $event = $this->generateEventName($key); - $this->event->listen($event, $listener); - } - } - } - - /** - * Check if the fired method has some notifications - * to send - * - * @param $notificationsResult - * @return bool - */ - public function hasNotificationToSend($notificationsResult) - { - return is_array($notificationsResult) - and count($notificationsResult) > 0 - and $notificationsResult[0] !== false - and count($notificationsResult[0]) > 0; - } - - /** - * Get Event name - * - * @param $eventName - * @return string - */ - protected function generateEventName($eventName) - { - return static::$defaultWildcard.".".str_replace('@', '.', $eventName); - } -} diff --git a/src/Notifynder/Handler/NotifynderEvent.php b/src/Notifynder/Handler/NotifynderEvent.php deleted file mode 100755 index 79e2df9..0000000 --- a/src/Notifynder/Handler/NotifynderEvent.php +++ /dev/null @@ -1,88 +0,0 @@ -event = $event; - $this->values = $values; - $this->category = $category; - } - - /** - * @return mixed - */ - public function getEvent() - { - return $this->event; - } - - /** - * Get a value from the given - * values - * - * @param $name - * @return mixed - */ - public function get($name) - { - if (array_key_exists($name, $this->values)) { - return $this->values[$name]; - } - - return null; - } - - /** - * @return string - */ - public function getCategory() - { - return $this->category; - } - - /** - * @param $name - * @return mixed - */ - public function __get($name) - { - return $this->get($name); - } - - /** - * @return NotifynderEvent - */ - public function getNotifynderEvent() - { - return $this; - } -} diff --git a/src/Notifynder/Handler/NotifynderHandler.php b/src/Notifynder/Handler/NotifynderHandler.php deleted file mode 100755 index ee2770e..0000000 --- a/src/Notifynder/Handler/NotifynderHandler.php +++ /dev/null @@ -1,124 +0,0 @@ -getNotifynderEvent(); - - $eventName = $this->getEventName($event->getEvent()); - - if ($this->listenerIsRegistered($eventName)) { - - // Make sure a notifynder instance is passed to the event - // invoker method - $notifynder = (is_null($notifynder)) ? $this->getNotifynder() : $notifynder; - - // Build the notifications - $builtNotifications = call_user_func_array([$this, $eventName], [$event, $notifynder]); - - // If the listener is the NotifynderEvent that means - // we are triggering this from the Notifynder::fire() - // Event, it will take care of sending the notification - if ($eventListener instanceof NotifynderEvent) { - return $builtNotifications; - } - - // Event has been dispatched manually from the native - // Laravel eventing system then I'll send the notification - // Right here - if ($this->hasNotificationToSend([$builtNotifications])) { - return $notifynder->send($builtNotifications); - } - } - - return null; - } - - /** - * Check if the listener exists on the class - * adding when as convention - * - * ['postAdd'] whenPostAdd] - * - * @param $eventName - * @return bool - */ - protected function listenerIsRegistered($eventName) - { - return method_exists($this, $eventName); - } - - /** - * Get Event Name from the key - * it use a convention - * - * given user.post.add -> postAdd - * given user@postAdd -> postAdd - * - * @param $event - * @return string - */ - protected function getEventName($event) - { - // Remove the Notiynder namespaces for - // the find the method - $event = str_replace(Dispatcher::$defaultWildcard.'.', '', $event); - - $eventNameSpace = (strpos($event, '@')) - ? explode('@', $event) - : explode('.', $event); - - // Check if the name has been splited in 2 - if (count($eventNameSpace) > 1) { - array_shift($eventNameSpace); - } - - $nameMethod = implode('_', $eventNameSpace); - - return camel_case($nameMethod); - } - - /** - * Get Notifynder Instance - * - * @return Notifynder - */ - protected function getNotifynder() - { - $notifynder = app('notifynder'); - - return $notifynder; - } - - /** - * Check if the fired method has some notifications - * to send - * - * @param $notificationsResult - * @return bool - */ - protected function hasNotificationToSend($notificationsResult) - { - return is_array($notificationsResult) - and count($notificationsResult) > 0 - and $notificationsResult[0] !== false - and count($notificationsResult[0]) > 0; - } -} diff --git a/src/Notifynder/Helpers/TypeChecker.php b/src/Notifynder/Helpers/TypeChecker.php new file mode 100644 index 0000000..ca2d318 --- /dev/null +++ b/src/Notifynder/Helpers/TypeChecker.php @@ -0,0 +1,128 @@ + 0) { + return true; + } + + if ($strict) { + throw new InvalidArgumentException('The value passed must be iterable'); + } + + return false; + } + + /** + * @param $notification + * @param bool $strict + * @return bool + * @throws InvalidArgumentException + */ + public static function isNotification($notification, $strict = true) + { + if (! is_a($notification, notifynder_config()->getNotificationModel())) { + if ($strict) { + throw new InvalidArgumentException('The value passed must be an Notification Model instance'); + } + + return false; + } + + return true; + } +} diff --git a/src/Notifynder/Helpers/helpers.php b/src/Notifynder/Helpers/helpers.php new file mode 100644 index 0000000..3b0ece9 --- /dev/null +++ b/src/Notifynder/Helpers/helpers.php @@ -0,0 +1,18 @@ +get($key, $default); + } +} diff --git a/src/Notifynder/Managers/NotifynderManager.php b/src/Notifynder/Managers/NotifynderManager.php new file mode 100755 index 0000000..e8aaecb --- /dev/null +++ b/src/Notifynder/Managers/NotifynderManager.php @@ -0,0 +1,135 @@ +sender = $sender; + } + + /** + * @param string|int|\Fenos\Notifynder\Models\NotificationCategory $category + * @return $this + */ + public function category($category) + { + $this->builder(true); + $this->builder->category($category); + + return $this; + } + + /** + * @param array|\Traversable $data + * @param Closure $callback + * @return $this + */ + public function loop($data, Closure $callback) + { + $this->builder(true); + $this->builder->loop($data, $callback); + + return $this; + } + + /** + * @param bool $force + * @return Builder + */ + public function builder($force = false) + { + if (is_null($this->builder) || $force) { + $this->builder = new Builder(); + } + + return $this->builder; + } + + /** + * @return bool + */ + public function send() + { + $sent = $this->sender->send($this->builder->getNotifications()); + $this->reset(); + + return (bool) $sent; + } + + /** + * @return SenderManagerContract + */ + public function sender() + { + return $this->sender; + } + + protected function reset() + { + $this->builder = null; + } + + /** + * @param string $name + * @param Closure $sender + * @return bool + */ + public function extend($name, Closure $sender) + { + return (bool) $this->sender->extend($name, $sender); + } + + /** + * @param $name + * @param $arguments + * @return $this|bool + * @throws BadMethodCallException + */ + public function __call($name, $arguments) + { + if (Str::startsWith($name, 'send')) { + $sent = $this->sender->sendWithCustomSender($name, $this->builder->getNotifications()); + $this->reset(); + + return (bool) $sent; + } + + if ($this->builder instanceof Builder && method_exists($this->builder, $name)) { + $result = call_user_func_array([$this->builder, $name], $arguments); + if (Str::startsWith($name, 'get')) { + return $result; + } + + return $this; + } + + $error = "The method [$name] doesn't exist in the class ".self::class; + throw new BadMethodCallException($error); + } +} diff --git a/src/Notifynder/Managers/SenderManager.php b/src/Notifynder/Managers/SenderManager.php new file mode 100644 index 0000000..a189706 --- /dev/null +++ b/src/Notifynder/Managers/SenderManager.php @@ -0,0 +1,103 @@ +sendSingle($notifications); + } + + return (bool) $this->sendMultiple($notifications); + } + + /** + * @param string $name + * @return bool + */ + public function hasSender($name) + { + return Arr::has($this->senders, $name); + } + + /** + * @param string $name + * @return Closure + */ + public function getSender($name) + { + return Arr::get($this->senders, $name); + } + + /** + * @param string $name + * @param Closure $sender + * @return bool + */ + public function extend($name, Closure $sender) + { + if (Str::startsWith($name, 'send')) { + $this->senders[$name] = $sender; + + return true; + } + + return false; + } + + /** + * @param string $name + * @param array $notifications + * @return bool + * @throws BadFunctionCallException + * @throws BadMethodCallException + */ + public function sendWithCustomSender($name, array $notifications) + { + if ($this->hasSender($name)) { + $sender = call_user_func_array($this->getSender($name), [$notifications]); + if ($sender instanceof SenderContract) { + return (bool) $sender->send($this); + } + throw new BadFunctionCallException("The sender [{$name}] hasn't returned an instance of ".SenderContract::class); + } + throw new BadMethodCallException("The sender [{$name}] isn't registered."); + } + + /** + * @param string $name + * @param array $arguments + * @return bool + * @throws BadMethodCallException + */ + public function __call($name, array $arguments) + { + if (array_key_exists(0, $arguments) && isset($arguments[0]) && is_array($arguments[0])) { + return $this->sendWithCustomSender($name, $arguments[0]); + } + + throw new BadMethodCallException('No argument passed to the custom sender, please provide notifications array'); + } +} diff --git a/src/Notifynder/Models/Notification.php b/src/Notifynder/Models/Notification.php index 3a3f886..308f048 100755 --- a/src/Notifynder/Models/Notification.php +++ b/src/Notifynder/Models/Notification.php @@ -1,55 +1,67 @@ - 'array', + ]; + + /** + * Notification constructor. * - * @param array $models - * @return NotifynderCollection|\Illuminate\Database\Eloquent\Collection + * @param array $attributes */ - public function newCollection(array $models = array()) + public function __construct($attributes = []) { - return new NotifynderCollection($models); + $this->fillable($this->mergeFillables()); + + if ($attributes instanceof BuilderNotification) { + $attributes = $attributes->toArray(); + } + + parent::__construct($attributes); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ - public function body() + public function category() { return $this->belongsTo(NotificationCategory::class, 'category_id'); } @@ -59,14 +71,11 @@ public function body() */ public function from() { - // check if on the configurations file there is the option - // polymorphic setted to true, if so Notifynder will work - // polymorphic. - if (config('notifynder.polymorphic') == false) { - return $this->belongsTo(config('notifynder.model'), 'from_id'); - } else { - return $this->morphTo(); + if (notifynder_config()->isPolymorphic()) { + return $this->morphTo('from'); } + + return $this->belongsTo(notifynder_config()->getNotifiedModel(), 'from_id'); } /** @@ -74,65 +83,99 @@ public function from() */ public function to() { - // check if on the configurations file there is the option - // polymorphic setted to true, if so Notifynder will work - // polymorphic. - if (config('notifynder.polymorphic') == false) { - return $this->belongsTo(config('notifynder.model'), 'to_id'); - } else { - return $this->morphTo(); + if (notifynder_config()->isPolymorphic()) { + return $this->morphTo('to'); } + + return $this->belongsTo(notifynder_config()->getNotifiedModel(), 'to_id'); } /** - * Not read scope - * - * @param $query - * @return mixed + * @return array */ - public function scopeWithNotRead($query) + public function getCustomFillableFields() { - return $query->where('read', 0); + return notifynder_config()->getAdditionalFields(); } /** - * Only Expired Notification scope - * - * @param $query - * @return mixed + * @return array */ - public function scopeOnlyExpired($query) + protected function mergeFillables() { - return $query->where('expire_time', '<', Carbon::now()); + $fillables = array_unique($this->getFillable() + $this->getCustomFillableFields()); + + return $fillables; } /** - * Where Polymorphic - * - * @param $query - * @param $id - * @param $type - * @return mixed + * @return string + * @throws \Fenos\Notifynder\Exceptions\ExtraParamsException */ - public function scopeWherePolymorphic($query, $id, $type) + public function getTextAttribute() { - if (! $type or config('notifynder.polymorphic') === false) { - return $query->where('to_id', $id); - } else { - return $query->where('to_id', $id) - ->where('to_type', $type); + if (! array_key_exists('text', $this->attributes)) { + $notifynderParse = new NotificationParser(); + $this->attributes['text'] = $notifynderParse->parse($this, $this->category_id); } + + return $this->attributes['text']; } /** - * Get parsed body attributes - * - * @return mixed + * @return bool|int */ - public function getNotifyBodyAttribute() + public function read() { - $notifynderParse = new NotifynderParser(); + return $this->update(['read' => 1]); + } - return $notifynderParse->parse($this); + /** + * @return bool|int + */ + public function unread() + { + return $this->update(['read' => 0]); + } + + /** + * @return bool + */ + public function resend() + { + $this->updateTimestamps(); + $this->read = 0; + + return $this->save(); + } + + /** + * @return bool + */ + public function isAnonymous() + { + return is_null($this->from_id); + } + + /** + * @param Builder $query + * @param $category + * @return Builder + */ + public function scopeByCategory(Builder $query, $category) + { + $categoryId = NotificationCategory::getIdByCategory($category); + + return $query->where('category_id', $categoryId); + } + + /** + * @param Builder $query + * @param int $read + * @return Builder + */ + public function scopeByRead(Builder $query, $read = 1) + { + return $query->where('read', $read); } } diff --git a/src/Notifynder/Models/NotificationCategory.php b/src/Notifynder/Models/NotificationCategory.php index fb833a1..7c660e9 100755 --- a/src/Notifynder/Models/NotificationCategory.php +++ b/src/Notifynder/Models/NotificationCategory.php @@ -1,56 +1,109 @@ - '', + ], $attributes); + + parent::__construct($attributes); + } + /** - * Relation with the notifications - * * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function notifications() { - return $this->hasMany('Fenos\Notifynder\Models\Notification', 'category_id'); + $config = app('notifynder.config'); + $model = $config->getNotificationModel(); + + return $this->hasMany($model, 'category_id'); + } + + public function setNameAttribute($value) + { + $parts = explode('.', $value); + foreach ($parts as $i => $part) { + $parts[$i] = Str::slug(preg_replace('/[^a-z0-9_]/', '_', strtolower($part)), '_'); + } + $this->attributes['name'] = implode('.', $parts); + } + + /** + * @return string + */ + public function getTemplateBodyAttribute() + { + if (notifynder_config()->isTranslated()) { + $key = notifynder_config()->getTranslationDomain().'.'.$this->name; + $trans = trans($key); + if ($trans != $key) { + return $trans; + } + } + + return $this->text; } /** - * Groups Categories - * - * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany + * @param Builder $query + * @param $name + * @return Builder */ - public function categories() + public function scopeByName(Builder $query, $name) { - return $this->belongsToMany( - 'Fenos\Notifynder\Models\NotificationGroup', - 'notifications_categories_in_groups', - 'category_id', - 'group_id' - ); + return $query->where('name', $name); + } + + /** + * @param string|int|\Fenos\Notifynder\Models\NotificationCategory $category + * @return int + */ + public static function getIdByCategory($category) + { + $categoryId = $category; + if ($category instanceof self) { + $categoryId = $category->getKey(); + } elseif (! is_numeric($category)) { + $categoryId = self::byName($category)->firstOrFail()->getKey(); + } + + return $categoryId; } } diff --git a/src/Notifynder/Models/NotificationGroup.php b/src/Notifynder/Models/NotificationGroup.php deleted file mode 100755 index bc81460..0000000 --- a/src/Notifynder/Models/NotificationGroup.php +++ /dev/null @@ -1,34 +0,0 @@ -belongsToMany( - 'Fenos\Notifynder\Models\NotificationCategory', - 'notifications_categories_in_groups', - 'group_id', 'category_id' - ); - } -} diff --git a/src/Notifynder/Models/NotifynderCollection.php b/src/Notifynder/Models/NotifynderCollection.php deleted file mode 100755 index a2d6fe5..0000000 --- a/src/Notifynder/Models/NotifynderCollection.php +++ /dev/null @@ -1,81 +0,0 @@ -items as $key => $item) { - try { - $translation = $this->translator() - ->translate($language, $this->items[$key]['body']['name']); - - $this->items[$key]['body']['text'] = $translation; - } catch (NotificationTranslationNotFoundException $e) { - $this->items[$key]['body']['text']; - } - } - - $this->parse(); - - return $this; - } - - /** - * Parse the body of the notification - * - * @return $this - */ - public function parse() - { - $parser = new NotifynderParser(); - - foreach ($this->items as $key => $item) { - - $this->items[$key]['text'] = $parser->parse($item); - } - - return $this; - } -} diff --git a/src/Notifynder/Notifable.php b/src/Notifynder/Notifable.php deleted file mode 100755 index c9d896a..0000000 --- a/src/Notifynder/Notifable.php +++ /dev/null @@ -1,146 +0,0 @@ -morphMany(config('notifynder.notification_model'), 'to'); - } else { - return $this->hasMany(config('notifynder.notification_model'), 'to_id'); - } - } - - /** - * Read all Notifications - * - * @return mixed - */ - public function readAllNotifications() - { - return $this->notifynderInstance()->entity( - $this->getMorphClass() - )->readAll($this->id); - } - - /** - * Read Limiting Notifications - * - * @param int $numbers - * @param string $order - * @return mixed - */ - public function readLimitNotifications($numbers = 10, $order = "ASC") - { - return $this->notifynderInstance()->entity( - $this->getMorphClass() - )->readLimit($this->id, $numbers, $order); - } - - /** - * Delete Limiting Notifications - * - * @param int $numbers - * @param string $order - * @return mixed - */ - public function deleteLimitNotifications($numbers = 10, $order = "ASC") - { - return $this->notifynderInstance()->entity( - $this->getMorphClass() - )->deleteLimit($this->id, $numbers, $order); - } - - /** - * Delete all Notifications - * - * @return Bool - */ - public function deleteAllNotifications() - { - return $this->notifynderInstance()->entity( - $this->getMorphClass() - )->deleteAll($this->id); - } - - /** - * Get Not Read - * - * @param null $limit - * @param int|null $paginate - * @param string $order - * @return mixed - */ - public function getNotificationsNotRead($limit = null, $paginate = null, $order = 'desc') - { - return $this->notifynderInstance()->entity( - $this->getMorphClass() - )->getNotRead($this->id, $limit, $paginate, $order); - } - - /** - * Get all notifications - * - * @param null $limit - * @param int|null $paginate - * @param string $order - * @return mixed - */ - public function getNotifications($limit = null, $paginate = null, $order = 'desc') - { - return $this->notifynderInstance()->entity( - $this->getMorphClass() - )->getAll($this->id, $limit, $paginate, $order); - } - - /** - * Get last notification - * - * @param null $category - * @return mixed - */ - public function getLastNotification($category = null) - { - return $this->notifynderInstance()->entity( - $this->getMorphClass() - )->getLastNotification($this->id,$category); - } - - /** - * Count Not read notification - * - * @return mixed - */ - public function countNotificationsNotRead() - { - return $this->notifynderInstance()->entity( - $this->getMorphClass() - )->countNotRead($this->id); - } - - /** - * @return \Fenos\Notifynder\NotifynderManager - */ - protected function notifynderInstance() - { - return app('notifynder'); - } -} diff --git a/src/Notifynder/Notifications/NotificationManager.php b/src/Notifynder/Notifications/NotificationManager.php deleted file mode 100755 index bffbca5..0000000 --- a/src/Notifynder/Notifications/NotificationManager.php +++ /dev/null @@ -1,273 +0,0 @@ -notifynderRepo = $notifynderRepo; - } - - /** - * Set the entity for polymorphic - * - * @param $name - * @return $this - */ - public function entity($name) - { - $this->entity = $name; - - return $this; - } - - /** - * Find a notification by ID - * - * @param $notification_id - * @return NotificationModel|\Illuminate\Database\Eloquent\Model|static - * @throws \Fenos\Notifynder\Exceptions\NotificationNotFoundException - */ - public function find($notification_id) - { - $notification = $this->notifynderRepo->find($notification_id); - - if (is_null($notification)) { - $error = "Notification Not found"; - throw new NotificationNotFoundException($error); - } - - return $notification; - } - - /** - * Make read one notification giving - * the ID of it - * - * @param $notification_id - * @return bool|\Fenos\Notifynder\Models\Notification - */ - public function readOne($notification_id) - { - $notification = $this->find($notification_id); - - return $this->notifynderRepo->readOne($notification); - } - - /** - * Read notifications in base the number - * Given - * - * @param $to_id - * @param $numbers - * @param string $order - * @return mixed - */ - public function readLimit($to_id, $numbers, $order = "ASC") - { - return $this->notifynderRepo->readLimit($to_id, $this->entity, $numbers, $order); - } - - /** - * Read all notification of the - * given entity - * - * @param $to_id - * @return Number - */ - public function readAll($to_id) - { - return $this->notifynderRepo->readAll($to_id, $this->entity); - } - - /** - * Delete a notification giving the id - * of it - * - * @param $notification_id - * @return Bool - */ - public function delete($notification_id) - { - return $this->notifynderRepo->delete($notification_id); - } - - /** - * Delete numbers of notifications equals - * to the number passing as 2 parameter of - * the current user - * - * @param $entity_id - * @param $number - * @param $order - * @return mixed - */ - public function deleteLimit($entity_id, $number, $order = 'asc') - { - return $this->notifynderRepo->deleteLimit($entity_id, $this->entity, $number, $order); - } - - /** - * Delete all notification of a given - * Entity - * - * @param $entity_id - * @return Bool - */ - public function deleteAll($entity_id) - { - return $this->notifynderRepo->deleteAll($entity_id, $this->entity); - } - - /** - * Delete All notifications from a - * defined category - * - * @param $category_name string - * @param $expired Bool - * @return Bool - */ - public function deleteByCategory($category_name, $expired = false) - { - return $this->notifynderRepo->deleteByCategory($category_name, $expired); - } - - /** - * Get notifications not read - * of the entity given - * - * @param $to_id - * @param $limit - * @param int|null $paginate - * @param string $orderDate - * @return mixed - */ - public function getNotRead($to_id, $limit = null, $paginate = null, $orderDate = 'desc') - { - $notifications = $this->notifynderRepo->getNotRead( - $to_id, $this->entity, - $limit, $paginate, $orderDate - ); - - if(is_int(intval($paginate)) && !is_null($paginate)) - { - return (new Paginator($notifications->parse(), $limit, $paginate, [ - 'path' => Paginator::resolveCurrentPath(), - ])); - } - - return $notifications->parse(); - } - - /** - * Get All notifications - * - * @param $to_id - * @param $limit - * @param int|null $paginate - * @param string $orderDate - * @return mixed - */ - public function getAll($to_id, $limit = null, $paginate = null, $orderDate = 'desc') - { - $notifications = $this->notifynderRepo->getAll( - $to_id, $this->entity, - $limit, $paginate, $orderDate - ); - - if(is_int(intval($paginate)) && !is_null($paginate)) - { - return (new Paginator($notifications->parse(), $limit, $paginate, [ - 'path' => Paginator::resolveCurrentPath(), - ])); - } - - return $notifications->parse(); - } - - /** - * Get last notification of the - * given entity - * - * @param $to_id - * @return mixed - */ - public function getLastNotification($to_id) - { - return $this->notifynderRepo->getLastNotification($to_id,$this->entity); - } - - /** - * Get last notification of the - * given entity of the specific category - * - * @param $category - * @param $to_id - * @return mixed - */ - public function getLastNotificationByCategory($category,$to_id) - { - return $this->notifynderRepo->getLastNotificationByCategory($category,$to_id,$this->entity); - } - - /** - * Send single notification - * - * @param array $info - * @return static - */ - public function sendOne(array $info) - { - return $this->notifynderRepo->storeSingle($info); - } - - /** - * Send multiple notifications - * - * @param array $info - * @return mixed - */ - public function sendMultiple(array $info) - { - return $this->notifynderRepo->storeMultiple($info); - } - - /** - * Get number of notification - * not read - * - * @param $to_id - * @return mixed - */ - public function countNotRead($to_id) - { - return $this->notifynderRepo->countNotRead($to_id, $this->entity); - } -} diff --git a/src/Notifynder/Notifications/NotificationRepository.php b/src/Notifynder/Notifications/NotificationRepository.php deleted file mode 100755 index 48af0af..0000000 --- a/src/Notifynder/Notifications/NotificationRepository.php +++ /dev/null @@ -1,328 +0,0 @@ -notification = $notification; - $this->db = $db; - } - - /** - * Find notification by id - * - * @param $notification_id - * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|static - */ - public function find($notification_id) - { - return $this->notification->find($notification_id); - } - - /** - * Save a single notification sent - * - * @param array $info - * @return Notification - */ - public function storeSingle(array $info) - { - return $this->notification->create($info); - } - - /** - * Save multiple notifications sent - * at once - * - * @param array $info - * @return mixed - */ - public function storeMultiple(array $info) - { - return $this->db->table( - $this->notification->getTable() - )->insert($info); - } - - /** - * Make Read One Notification - * - * @param Notification $notification - * @return bool|Notification - */ - public function readOne(Notification $notification) - { - $notification->read = 1; - - if ($notification->save()) { - return $notification; - } - - return false; - } - - /** - * Read notifications in base the number - * Given - * - * @param $to_id - * @param $entity - * @param $numbers - * @param $order - * @return int - */ - public function readLimit($to_id, $entity, $numbers, $order) - { - $notifications = $this->notification->withNotRead() - ->wherePolymorphic($to_id, $entity) - ->limit($numbers) - ->orderBy('id', $order) - ->lists('id'); - - return $this->notification->whereIn('id', $notifications) - ->update(['read' => 1]); - } - - /** - * Make read all notification not read - * - * @param $to_id - * @param $entity - * @return int - */ - public function readAll($to_id, $entity) - { - return $this->notification->withNotRead() - ->wherePolymorphic($to_id, $entity) - ->update(['read' => 1]); - } - - /** - * Delete a notification giving the id - * of it - * - * @param $notification_id - * @return Bool - */ - public function delete($notification_id) - { - return $this->notification->where('id', $notification_id)->delete(); - } - - /** - * Delete All notifications about the - * current user - * - * @param $to_id int - * @param $entity - * @return Bool - */ - public function deleteAll($to_id, $entity) - { - $query = $this->db->table( - $this->notification->getTable() - ); - - return $this->notification->scopeWherePolymorphic($query, $to_id, $entity) - ->delete(); - } - - /** - * Delete All notifications from a - * defined category - * - * @param $category_name int - * @param $expired Bool - * @return Bool - */ - public function deleteByCategory($category_name, $expired = false) - { - $query = $this->notification->whereHas('body', function ($q) use ($category_name) { - $q->where('name', $category_name); - }); - - if ($expired == true) { - return $query->onlyExpired()->delete(); - } - - return $query->delete(); - } - - /** - * - * Delete numbers of notifications equals - * to the number passing as 2 parameter of - * the current user - * - * @param $user_id int - * @param $entity - * @param $number int - * @param $order string - * @return int - * @throws \Exception - */ - public function deleteLimit($user_id, $entity, $number, $order) - { - $notifications_ids = $this->notification - ->wherePolymorphic($user_id, $entity) - ->orderBy('id', $order) - ->select('id') - ->limit($number)->lists('id'); - - if (count($notifications_ids) == 0) { - return false; - } - - return $this->notification->whereIn('id', $notifications_ids) - ->delete(); - } - - /** - * Retrive notifications not Read - * You can also limit the number of - * Notification if you don't it will get all - * - * @param $to_id - * @param $entity - * @param int|null $limit - * @param int|null $paginate - * @param string $orderDate - * @return mixed - */ - public function getNotRead($to_id, $entity, $limit = null, $paginate = null, $orderDate = 'desc') - { - $result = $this->notification->with('body', 'from') - ->wherePolymorphic($to_id, $entity) - ->withNotRead() - ->orderBy('read', 'ASC') - ->orderBy('created_at', $orderDate); - - if (! is_null($limit)) { - $result->limit($limit); - } - - if(is_int(intval($paginate)) && !is_null($paginate)) - { - $result->skip(($paginate - 1) * $limit)->take($limit + 1); - } - - return $result->get(); - } - - /** - * Retrive all notifications, not read - * in first. - * You can also limit the number of - * Notifications if you don't, it will get all - * - * @param $to_id - * @param $entity - * @param null $limit - * @param int|null $paginate - * @param string $orderDate - * @return mixed - */ - public function getAll($to_id, $entity, $limit = null, $paginate = null, $orderDate = 'desc') - { - $result = $this->notification->with('body', 'from') - ->wherePolymorphic($to_id, $entity) - ->orderBy('read', 'ASC') - ->orderBy('created_at', $orderDate); - - // if the limit is set - if (! is_null($limit)) { - $result->limit($limit); - } - - if(is_int(intval($paginate)) && !is_null($paginate)) - { - $result->skip(($paginate - 1) * $limit)->take($limit + 1); - } - - return $result->get(); - } - - /** - * get number Notifications - * not read - * - * @param $to_id - * @param $entity - * @return mixed - */ - public function countNotRead($to_id, $entity) - { - return $this->notification->wherePolymorphic($to_id, $entity) - ->withNotRead() - ->select($this->db->raw('Count(*) as notRead')) - ->count(); - } - - /** - * Get last notification of the current - * entity - * - * @param $to_id - * @param $entity - * @return mixed - */ - public function getLastNotification($to_id,$entity) - { - return $this->notification->wherePolymorphic($to_id, $entity) - ->orderBy('created_at','DESC') - ->first(); - } - - /** - * Get last notification of the current - * entity of a specific category - * - * @param $category - * @param $to_id - * @param $entity - * @return mixed - */ - public function getLastNotificationByCategory($category,$to_id,$entity) - { - $query = $this->notification->wherePolymorphic($to_id, $entity); - - if (is_numeric($category)) { - - return $query->orderBy('created_at','desc') - ->where('category_id',$category)->first(); - } - - return $query->whereHas('body', function($categoryQuery) use ($category) { - $categoryQuery->where('name',$category); - })->orderBy('created_at','desc')->first(); - } -} diff --git a/src/Notifynder/Notifynder.php b/src/Notifynder/Notifynder.php deleted file mode 100755 index f0f3cd1..0000000 --- a/src/Notifynder/Notifynder.php +++ /dev/null @@ -1,316 +0,0 @@ -send() if u pass 'sendCustom' - * it will be like $notifynder->sendCustom() - * - * @param $customSenderName - * @return $this - */ - public function dipatchWith($customSenderName); -} diff --git a/src/Notifynder/NotifynderManager.php b/src/Notifynder/NotifynderManager.php deleted file mode 100755 index f7a583a..0000000 --- a/src/Notifynder/NotifynderManager.php +++ /dev/null @@ -1,626 +0,0 @@ -notifynderCategory = $notifynderCategory; - $this->notifynderSender = $notifynderSender; - $this->notification = $notification; - $this->notifynderDispatcher = $notifynderDispatcher; - $this->notifynderGroup = $notifynderGroup; - - parent::__construct($notifynderCategory); - } - - /** - * Set the category of the - * notification - * - * @param $name - * @return $this - */ - public function category($name) - { - // Check if the category is lazy loaded - if ($this->isLazyLoaded($name)) { - // Yes it is, split out the value from the array - $this->defaultCategory = $this->getCategoriesContainer($name); - - // set category on the builder - parent::category($this->defaultCategory->id); - - return $this; - } - - // Otherwise ask to the db and give me the right category - // associated with this name. If the category is not found - // it throw CategoryNotFoundException - $category = $this->notifynderCategory->findByName($name); - - $this->defaultCategory = $category; - - // Set the category on the array - $this->setCategoriesContainer($name, $category); - - // set category on the builder - parent::category($category->id); - - return $this; - } - - /** - * Define an entity when Notifynder is - * used Polymorpically - * - * @param $name - * @return $this - */ - public function entity($name) - { - $this->entity = $name; - - return $this; - } - - /** - * Add a category - * - * @param $name - * @param $text - * @return static - */ - public function addCategory($name, $text) - { - return $this->notifynderCategory->add($name, $text); - } - - /** - * Update a category - * - * @param array $updates - * @param $id - * @return mixed - */ - public function updateCategory(array $updates, $id) - { - return $this->notifynderCategory->update($updates, $id); - } - - /** - * Send notifications - * Both multiple and single - * - * @param array $info - * @return mixed - */ - public function send($info = []) - { - $info = (count($info) > 0) ? $info : $this->toArray(); - - return $this->notifynderSender->send($info, $this->defaultCategory); - } - - /** - * Send immediately the notification - * even if the queue is enabled - * - * @param array $info - * @return mixed - */ - public function sendNow($info = []) - { - $info = (count($info) > 0) ? $info : $this->toArray(); - - return $this->notifynderSender->sendNow($info, $this->defaultCategory); - } - - /** - * Send One notification - * - * @param array $info - * @return mixed - */ - public function sendOne($info = []) - { - $info = (count($info) > 0) ? $info : $this->toArray(); - - return $this->notifynderSender->sendOne($info, $this->defaultCategory); - } - - /** - * Send multiple notifications - * - * @param array $info - * @return Senders\SendMultiple - */ - public function sendMultiple($info = []) - { - $info = (count($info) > 0) ? $info : $this->toArray(); - - return $this->notifynderSender->sendMultiple($info, $this->defaultCategory); - } - - /** - * Send a group of notifications - * - * @param $group_name - * @param $info - * @return mixed - */ - public function sendGroup($group_name, $info = []) - { - $info = (count($info) > 0) ? $info : $this->toArray(); - - return $this->notifynderSender->sendGroup($this, $group_name, $info); - } - - /** - * Read one notification - * - * @param $notification_id - * @return bool|Models\Notification - */ - public function readOne($notification_id) - { - return $this->notification->readOne($notification_id); - } - - /** - * Read notification in base the number - * Given - * - * @param $to_id - * @param $numbers - * @param string $order - * @return mixed - */ - public function readLimit($to_id, $numbers, $order = "ASC") - { - $notification = $this->notification->entity($this->entity); - - return $notification->readLimit($to_id, $numbers, $order); - } - - /** - * Read all notifications of the given - * entity - * - * @param $to_id - * @return Number - */ - public function readAll($to_id) - { - $notifications = $this->notification->entity($this->entity); - - return $notifications->readAll($to_id); - } - - /** - * Delete a single notification - * - * @param $notification_id - * @return Bool - */ - public function delete($notification_id) - { - return $this->notification->delete($notification_id); - } - - /** - * Delete number of notifications - * secified of the given entity - * - * @param $to_id - * @param $number - * @param string $order - * @return mixed - */ - public function deleteLimit($to_id, $number, $order = "ASC") - { - $notifications = $this->notification->entity($this->entity); - - return $notifications->deleteLimit($to_id, $number, $order); - } - - /** - * Delete all notifications - * of the the given entity - * - * @param $to_id - * @return Bool - */ - public function deleteAll($to_id) - { - $notifications = $this->notification->entity($this->entity); - - return $notifications->deleteAll($to_id); - } - - /** - * Delete All notifications from a - * defined category - * - * @param $category_name string - * @param $expired Bool - * @return Bool - */ - public function deleteByCategory($category_name, $expired = false) - { - return $this->notification->deleteByCategory($category_name, $expired); - } - - /** - * Get Notifications not read - * of the given entity - * - * @param $to_id - * @param null $limit - * @param null|int $paginate - * @param string $order - * @return mixed - */ - public function getNotRead($to_id, $limit = null, $paginate = null, $order = "desc") - { - $notifications = $this->notification->entity($this->entity); - - return $notifications->getNotRead($to_id, $limit, $paginate, $order); - } - - /** - * Get all notifications of the - * given entity - * - * @param $to_id - * @param null $limit - * @param int|null $paginate - * @param string $order - * @return mixed - */ - public function getAll($to_id, $limit = null, $paginate = null, $order = "desc") - { - $notifications = $this->notification->entity($this->entity); - - return $notifications->getAll($to_id, $limit, $paginate); - } - - /** - * Get number of notification not read - * of the given entity - * - * @param $to_id - * @return mixed - */ - public function countNotRead($to_id) - { - $notifications = $this->notification->entity($this->entity); - - return $notifications->countNotRead($to_id); - } - - /** - * Find Notification by ID - * - * @param $notification_id - * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|static - */ - public function findNotificationById($notification_id) - { - return $this->notification->find($notification_id); - } - - /** - * Get last notification of the given - * entity, second parameter can filter by - * category - * - * @param $to_id - * @param null $category - * @return mixed - */ - public function getLastNotification($to_id,$category = null) - { - $notification = $this->notification->entity($this->entity); - - if ( is_null($category)) { - return $notification->getLastNotification($to_id); - } - - return $notification->getLastNotificationByCategory($category,$to_id); - } - - /** - * Add category to a group - * giving the names of them - * - * @param $gorup_name - * @param $category_name - * @return mixed - */ - public function addCategoryToGroupByName($gorup_name, $category_name) - { - return $this->notifynderGroup->addCategoryToGroupByName($gorup_name, $category_name); - } - - /** - * Add category to a group - * giving the ids of them - * - * @param $gorup_id - * @param $category_id - * @return mixed - */ - public function addCategoryToGroupById($gorup_id, $category_id) - { - return $this->notifynderGroup->addCategoryToGroupById($gorup_id, $category_id); - } - - /** - * Add categories to a group having as first parameter - * the name of the group, and others as name - * categories - * - * @return mixed - */ - public function addCategoriesToGroup() - { - return $this->notifynderGroup->addMultipleCategoriesToGroup(func_get_args()); - } - - /** - * Fire method for fire listeners - * of logic - * - * @param string $key - * @param string $category_name - * @param mixed|null $values - * @return mixed|null - */ - public function fire($key, $category_name, $values = []) - { - return $this->notifynderDispatcher->sendWith($this->eventSender) - ->fire($this, $key, $category_name, $values); - } - - /** - * Associate events to categories - * - * @param $data - * @param array $delegation - * @return mixed - */ - public function delegate(array $delegation, $data = []) - { - return $this->notifynderDispatcher->delegate($this, $data, $delegation); - } - - /** - * Boot Listeners - * - * @param array $listeners - */ - public function bootListeners(array $listeners) - { - $this->notifynderDispatcher->boot($listeners); - } - - /** - * Get instance of the notifynder builder - * - * @return NotifynderBuilder - */ - public function builder() - { - return new parent($this->notifynderCategory); - } - - /** - * Extend a custom sender method - * - * @param $name - * @param callable $registrar - * @return $this - */ - public function extend($name, $registrar) - { - if (! starts_with($name, 'send')) { - $error = "The sender method must start with [send]"; - throw new InvalidArgumentException($error); - } - - $this->notifynderSender->extend($name, $registrar); - - return $this; - } - - /** - * Check if the category is eager Loaded - * - * @param $name - * @return bool - */ - protected function isLazyLoaded($name) - { - return array_key_exists($name, $this->categoriesContainer); - } - - /** - * Return the Id of the category - * - * @return mixed - */ - public function id() - { - return $this->defaultCategory->id; - } - - /** - * Push a category in the categoriesContainer - * property - * - * @param $name - * @param array $categoriesContainer - */ - protected function setCategoriesContainer($name, $categoriesContainer) - { - $this->categoriesContainer[$name] = $categoriesContainer; - } - - /** - * Get the categoriesContainer property - * - * @param $name - * @return array - */ - public function getCategoriesContainer($name) - { - return $this->categoriesContainer[$name]; - } - - /** - * Define which method - * the event dispatcher has - * to send the notifications - * - * @param $customSenderName - * @return $this - */ - public function dipatchWith($customSenderName) - { - $this->eventSender = $customSenderName; - - return $this; - } - - /** - * Call the custom sender method - * - * @param $name - * @param $arguments - * @return void|mixed - */ - public function __call($name, $arguments) - { - if (starts_with($name, 'send')) { - - $arguments = (isset($arguments[0])) ? $arguments[0] : $this->toArray(); - - return $this->notifynderSender->customSender($name,$arguments); - } - - $error = "method [$name] not found in the class ".self::class; - throw new BadMethodCallException($error); - } - - /** - * Set builder properties - * When setting dynamic properties - * - * @param $name - * @param $value - */ - function __set($name, $value) - { - $this->offsetSet($name,$value); - } - - /** - * Get property from the - * builder - * - * @param $name - * @return mixed - */ - function __get($name) - { - return $this->offsetGet($name); - } -} diff --git a/src/Notifynder/NotifynderServiceProvider.php b/src/Notifynder/NotifynderServiceProvider.php index 9cc01ae..1b2cf0b 100755 --- a/src/Notifynder/NotifynderServiceProvider.php +++ b/src/Notifynder/NotifynderServiceProvider.php @@ -1,295 +1,188 @@ - '2014_02_10_145728_notification_categories', + 'CreateNotificationGroupsTable' => '2014_08_01_210813_create_notification_groups_table', + 'CreateNotificationCategoryNotificationGroupTable' => '2014_08_01_211045_create_notification_category_notification_group_table', + 'CreateNotificationsTable' => '2015_05_05_212549_create_notifications_table', + 'AddExpireTimeColumnToNotificationTable' => '2015_06_06_211555_add_expire_time_column_to_notification_table', + 'ChangeTypeToExtraInNotificationsTable' => '2015_06_06_211555_change_type_to_extra_in_notifications_table', + 'AlterCategoryNameToUnique' => '2015_06_07_211555_alter_category_name_to_unique', + 'MakeNotificationUrlNullable' => '2016_04_19_200827_make_notification_url_nullable', + 'AddStackIdToNotifications' => '2016_05_19_144531_add_stack_id_to_notifications', + 'UpdateVersion4NotificationsTable' => '2016_07_01_153156_update_version4_notifications_table', + 'DropVersion4UnusedTables' => '2016_11_02_193415_drop_version4_unused_tables', + ]; /** - * Register Bindings + * Register the service provider. + * + * @return void */ public function register() { - $this->notifynder(); - $this->senders(); - $this->notifications(); - $this->categories(); - $this->builder(); - $this->groups(); - $this->translator(); - $this->events(); - $this->contracts(); - $this->artisan(); + $this->bindContracts(); + $this->bindConfig(); + $this->bindSender(); + $this->bindNotifynder(); + + $this->registerSenders(); } - /* - * Boot the publishing config + /** + * Boot the service provider. + * + * @return void */ public function boot() { $this->config(); + $this->migration(); } /** - * Bind Notifynder + * Bind contracts. + * + * @return void */ - protected function notifynder() + protected function bindContracts() { - $this->app->bindShared('notifynder', function ($app) { - return new NotifynderManager( - $app['notifynder.category'], - $app['notifynder.sender'], - $app['notifynder.notification'], - $app['notifynder.dispatcher'], - $app['notifynder.group'] - ); - }); - - // Register Facade - $this->app->alias('notifynder', 'Notifynder'); + $this->app->bind(NotifynderManagerContract::class, 'notifynder'); + $this->app->bind(SenderManagerContract::class, 'notifynder.sender'); + $this->app->bind(ConfigContract::class, 'notifynder.config'); } /** - * Bind Notifynder Categories to IoC + * Bind Notifynder config. + * + * @return void */ - protected function categories() + protected function bindConfig() { - $this->app->bindShared('notifynder.category', function ($app) { - return new CategoryManager( - $app->make('notifynder.category.repository') - ); - }); - - $this->app->bindShared('notifynder.category.repository', function ($app) { - return new CategoryRepository( - new NotificationCategory() - ); + $this->app->singleton('notifynder.config', function ($app) { + return new Config(); }); } /** - * Bind the notifications + * Bind Notifynder sender. + * + * @return void */ - protected function notifications() + protected function bindSender() { - $this->app->bindShared('notifynder.notification', function ($app) { - return new NotificationManager( - $app['notifynder.notification.repository'] - ); - }); - - $this->app->bindShared('notifynder.notification.repository', function ($app) { - - $notificationModel = $app['config']->get('notifynder.notification_model'); - $notificationIstance = $app->make($notificationModel); - - return new NotificationRepository( - $notificationIstance, - $app['db'] - ); + $this->app->singleton('notifynder.sender', function ($app) { + return new SenderManager(); }); - - // Default store notification - $this->app->bind('notifynder.store', 'notifynder.notification.repository'); } /** - * Bind Translator + * Bind Notifynder manager. + * + * @return void */ - protected function translator() + protected function bindNotifynder() { - $this->app->bindShared('notifynder.translator', function ($app) { - return new TranslatorManager( - $app['notifynder.translator.compiler'], - $app['config'] - ); - }); - - $this->app->bindShared('notifynder.translator.compiler', function ($app) { - return new Compiler( - $app['filesystem.disk'] + $this->app->singleton('notifynder', function ($app) { + return new NotifynderManager( + $app['notifynder.sender'] ); }); } /** - * Bind Senders + * Register the default senders. + * + * @return void */ - protected function senders() + public function registerSenders() { - $this->app->bindShared('notifynder.sender', function ($app) { - return new SenderManager( - $app['notifynder.sender.factory'], - $app['notifynder.store'], - $app[Container::class] - ); + app('notifynder')->extend('sendSingle', function (array $notifications) { + return new SingleSender($notifications); }); - $this->app->bindShared('notifynder.sender.factory', function ($app) { - return new SenderFactory( - $app['notifynder.group'], - $app['notifynder.category'] - ); + app('notifynder')->extend('sendMultiple', function (array $notifications) { + return new MultipleSender($notifications); }); - } - /** - * Bind Dispatcher - */ - protected function events() - { - $this->app->bindShared('notifynder.dispatcher', function ($app) { - return new Dispatcher( - $app['events'] - ); + app('notifynder')->extend('sendOnce', function (array $notifications) { + return new OnceSender($notifications); }); } /** - * Bind Groups + * Publish and merge config file. + * + * @return void */ - protected function groups() + protected function config() { - $this->app->bindShared('notifynder.group', function ($app) { - return new GroupManager( - $app['notifynder.group.repository'], - $app['notifynder.group.category'] - ); - }); - - $this->app->bindShared('notifynder.group.repository', function ($app) { - return new GroupRepository( - new NotificationGroup() - ); - }); + $this->publishes([ + __DIR__.'/../config/notifynder.php' => config_path('notifynder.php'), + ]); - $this->app->bindShared('notifynder.group.category', function ($app) { - return new GroupCategoryRepository( - $app['notifynder.category'], - new NotificationGroup() - ); - }); + $this->mergeConfigFrom(__DIR__.'/../config/notifynder.php', 'notifynder'); } /** - * Bind Builder + * Publish migration files. + * + * @return void */ - protected function builder() + protected function migration() { - $this->app->bindShared('notifynder.builder', function ($app) { - return new NotifynderBuilder( - $app['notifynder.category'] - ); - }); + foreach ($this->migrations as $class => $file) { + if (! class_exists($class)) { + $this->publishMigration($file); + } + } } /** - * Contracts of notifynder + * Publish a single migration file. + * + * @param string $filename + * @return void */ - protected function contracts() + protected function publishMigration($filename) { - // Notifynder - $this->app->bind(Notifynder::class, 'notifynder'); - - // Repositories - $this->app->bind(CategoryDB::class, 'notifynder.category.repository'); - $this->app->bind(NotificationDB::class, 'notifynder.notification.repository'); - $this->app->bind(NotifynderGroupDB::class, 'notifynder.group.repository'); - $this->app->bind(NotifynderGroupCategoryDB::class, 'notifynder.group.category'); - - // Main Classes - $this->app->bind(NotifynderCategory::class, 'notifynder.category'); - $this->app->bind(NotifynderNotification::class, 'notifynder.notification'); - $this->app->bind(NotifynderTranslator::class, 'notifynder.translator'); - $this->app->bind(NotifynderGroup::class, 'notifynder.group'); - - // Store notifications - $this->app->bind(StoreNotification::class, 'notifynder.store'); - $this->app->bind(NotifynderSender::class, 'notifynder.sender'); - $this->app->bind(NotifynderDispatcher::class, 'notifynder.dispatcher'); + $extension = '.php'; + $filename = trim($filename, $extension).$extension; + $stub = __DIR__.'/../migrations/'.$filename; + $target = $this->getMigrationFilepath($filename); + $this->publishes([$stub => $target], 'migrations'); } /** - * Publish config files + * Get the migration file path. + * + * @param string $filename + * @return string */ - protected function config() + protected function getMigrationFilepath($filename) { - $this->publishes([ - __DIR__.'/../config/notifynder.php' => config_path('notifynder.php'), - __DIR__.'/../migrations/' => base_path('/database/migrations'), - ]); - } - - /** - * Register Artisan commands - */ - protected function artisan() - { - // Categories - $this->app->bindShared('notifynder.artisan.category-add', function ($app) { - return new CreateCategory( - $app['notifynder.category'] - ); - }); - - $this->app->bindShared('notifynder.artisan.category-delete', function ($app) { - return new DeleteCategory( - $app['notifynder.category'] - ); - }); - - // Groups - $this->app->bindShared('notifynder.artisan.group-add', function ($app) { - return new CreateGroup( - $app['notifynder.group'] - ); - }); - - $this->app->bindShared('notifynder.artisan.group-add-categories', function ($app) { - return new PushCategoryToGroup( - $app['notifynder.group'], - new ArtisanOptionsParser() - ); - }); - - // Register commands - $this->commands([ - 'notifynder.artisan.category-add', - 'notifynder.artisan.category-delete', - 'notifynder.artisan.group-add', - 'notifynder.artisan.group-add-categories', - ]); + if (function_exists('database_path')) { + return database_path('/migrations/'.$filename); + } else { + return base_path('/database/migrations/'.$filename); // @codeCoverageIgnore + } } } diff --git a/src/Notifynder/Parsers/ArtisanOptionsParser.php b/src/Notifynder/Parsers/ArtisanOptionsParser.php deleted file mode 100755 index c5a4d06..0000000 --- a/src/Notifynder/Parsers/ArtisanOptionsParser.php +++ /dev/null @@ -1,57 +0,0 @@ - $field) { - // Example: - // name:string:nullable => ['name', 'string', 'nullable'] - // name:string(15):nullable - $chunks = preg_split('/\s?:\s?/', $field, null); - - // The first item will be our property - $property = array_shift($chunks); - - $args = null; - - // Finally, anything that remains will - // be our decorators - $decorators = $chunks; - - $parsed[$index] = $property; - - if (isset($args)) { - $parsed[$index]['args'] = $args; - } - if ($decorators) { - $parsed[$index]['decorators'] = $decorators; - } - } - - return $parsed; - } -} diff --git a/src/Notifynder/Parsers/NotificationParser.php b/src/Notifynder/Parsers/NotificationParser.php new file mode 100644 index 0000000..b345b03 --- /dev/null +++ b/src/Notifynder/Parsers/NotificationParser.php @@ -0,0 +1,107 @@ +template_body; + + $specialValues = $this->getValues($text); + if (count($specialValues) > 0) { + $specialValues = array_filter($specialValues, function ($value) use ($notification) { + return ((is_array($notification) && isset($notification[$value])) || (is_object($notification) && isset($notification->$value))) || starts_with($value, ['extra.', 'to.', 'from.']); + }); + + foreach ($specialValues as $replacer) { + $replace = $this->mixedGet($notification, $replacer); + if (empty($replace) && notifynder_config()->isStrict()) { + throw new ExtraParamsException("The following [$replacer] param required from your category is missing."); + } + $text = $this->replace($text, $replace, $replacer); + } + } + + return $text; + } + + /** + * Get an array of all placehodlers. + * + * @param string $body + * @return array + */ + protected function getValues($body) + { + $values = []; + preg_match_all(self::RULE, $body, $values); + + return $values[1]; + } + + /** + * Replace a single placeholder. + * + * @param string $body + * @param string $valueMatch + * @param string $replacer + * @return string + */ + protected function replace($body, $valueMatch, $replacer) + { + $body = str_replace('{'.$replacer.'}', $valueMatch, $body); + + return $body; + } + + /** + * @param array|object $object + * @param string $key + * @param null|mixed $default + * @return mixed + */ + protected function mixedGet($object, $key, $default = null) + { + if (is_null($key) || trim($key) == '') { + return ''; + } + foreach (explode('.', $key) as $segment) { + if (is_object($object) && isset($object->{$segment})) { + $object = $object->{$segment}; + } elseif (is_object($object) && method_exists($object, '__get') && ! is_null($object->__get($segment))) { + $object = $object->__get($segment); + } elseif (is_object($object) && method_exists($object, 'getAttribute') && ! is_null($object->getAttribute($segment))) { + $object = $object->getAttribute($segment); + } elseif (is_array($object) && array_key_exists($segment, $object)) { + $object = array_get($object, $segment, $default); + } else { + return value($default); + } + } + + return $object; + } +} diff --git a/src/Notifynder/Parsers/NotifynderParser.php b/src/Notifynder/Parsers/NotifynderParser.php deleted file mode 100755 index 873f1f1..0000000 --- a/src/Notifynder/Parsers/NotifynderParser.php +++ /dev/null @@ -1,140 +0,0 @@ -getValues($body); - - if ($specialValues > 0) { - - list($extrasToReplace, $relationsToReplace) = $this->categorizeSpecialValues($specialValues); - - $body = $this->replaceExtraValues($extrasToReplace, $extra, $body); - $body = $this->replaceValuesRelations($item, $relationsToReplace, $body); - } - - return $body; - } - - /** - * I categorize into 2 arrays - * the relations values - * and extras values - * - * @param $specialValues - * @return array - */ - protected function categorizeSpecialValues($specialValues) - { - $extrasToReplace = []; - $relationsToReplace = []; - - foreach ($specialValues as $specialValue) { - - if (starts_with($specialValue, 'extra.')) { - $extrasToReplace[] = $specialValue; - } else { - if (starts_with($specialValue, 'to.') or - starts_with($specialValue, 'from.') - ) { - $relationsToReplace[] = $specialValue; - } - } - } - - return array($extrasToReplace, $relationsToReplace); - } - - /** - * This method replace extra values - * of the given extra values specified - * in the extra field of the notification - * (parsed from Json) I use a convention - * to keep all the extras values under - * an {extra.*} namespace - * - * @param $extrasToReplace - * @param $extra - * @param $body - * @return array - */ - protected function replaceExtraValues($extrasToReplace, $extra, $body) - { - // replace the values specified in the extra - // wildcard - foreach ($extrasToReplace as $replacer) { - $valueMatch = explode('.', $replacer)[1]; - - if (array_key_exists($valueMatch, $extra)) { - - $body = str_replace('{'.$replacer.'}', $extra->{$valueMatch}, $body); - } - } - - return $body; - } - - /** - * Replace relations values as - * 'to' and 'from', that means you - * can have parsed value from the current - * relation {to.name} name who received - * notification - * - * @param $item - * @param $relationsToReplace - * @param $body - * @return mixed - */ - protected function replaceValuesRelations($item, $relationsToReplace, $body) - { - foreach ($relationsToReplace as $replacer) { - $valueMatch = explode('.', $replacer); - $relation = $valueMatch[0]; - $field = $valueMatch[1]; - - $body = str_replace('{'.$replacer.'}', $item[$relation][$field], $body); - } - - return $body; - } - - /** - * Get the values between {} - * and return an array of it - * - * @param $body - * @return mixed - */ - protected function getValues($body) - { - $values = []; - preg_match_all(self::RULE, $body, $values); - - return $values[1]; - } -} \ No newline at end of file diff --git a/src/Notifynder/Senders/MultipleSender.php b/src/Notifynder/Senders/MultipleSender.php new file mode 100644 index 0000000..3046878 --- /dev/null +++ b/src/Notifynder/Senders/MultipleSender.php @@ -0,0 +1,60 @@ +notifications = $notifications; + $this->database = app('db'); + } + + /** + * Send all notifications. + * + * @param SenderManagerContract $sender + * @return bool + */ + public function send(SenderManagerContract $sender) + { + $model = notifynder_config()->getNotificationModel(); + $table = (new $model())->getTable(); + + $this->database->beginTransaction(); + $stackId = $this->database + ->table($table) + ->max('stack_id') + 1; + foreach ($this->notifications as $key => $notification) { + $this->notifications[$key] = $this->notifications[$key]->toDbArray(); + $this->notifications[$key]['stack_id'] = $stackId; + } + $insert = $this->database + ->table($table) + ->insert($this->notifications); + $this->database->commit(); + + return (bool) $insert; + } +} diff --git a/src/Notifynder/Senders/OnceSender.php b/src/Notifynder/Senders/OnceSender.php new file mode 100644 index 0000000..176a3b5 --- /dev/null +++ b/src/Notifynder/Senders/OnceSender.php @@ -0,0 +1,91 @@ +notifications = $notifications; + } + + /** + * Send the notification once. + * + * @param SenderManagerContract $sender + * @return bool + */ + public function send(SenderManagerContract $sender) + { + $success = true; + foreach ($this->notifications as $notification) { + $query = $this->getQuery($notification); + if (! $query->exists()) { + $success = $sender->send([$notification]) ? $success : false; + } else { + $query->firstOrFail()->resend(); + } + } + + return $success; + } + + /** + * Get the base query. + * + * @param Notification $notification + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function getQuery(Notification $notification) + { + $query = $this->getQueryInstance(); + $query + ->where('from_id', $notification->from_id) + ->where('from_type', $notification->from_type) + ->where('to_id', $notification->to_id) + ->where('to_type', $notification->to_type) + ->where('category_id', $notification->category_id); + $extra = $notification->extra; + if (! is_null($extra) && ! empty($extra)) { + if (is_array($extra)) { + $extra = json_encode($extra); + } + $query->where('extra', $extra); + } + + return $query; + } + + /** + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function getQueryInstance() + { + $model = notifynder_config()->getNotificationModel(); + $query = $model::query(); + if (! ($query instanceof EloquentBuilder)) { + throw new BadMethodCallException("The query method hasn't return an instance of [".EloquentBuilder::class.'].'); + } + + return $query; + } +} diff --git a/src/Notifynder/Senders/SendGroup.php b/src/Notifynder/Senders/SendGroup.php deleted file mode 100755 index d0ba58c..0000000 --- a/src/Notifynder/Senders/SendGroup.php +++ /dev/null @@ -1,83 +0,0 @@ -info = $info; - $this->nameGroup = $nameGroup; - $this->notifynderGroup = $notifynderGroup; - $this->notifynderCategory = $notifynderCategory; - } - - /** - * Send group notifications - * - * @param StoreNotification $sender - * @return mixed - */ - public function send(StoreNotification $sender) - { - // Get group - $group = $this->notifynderGroup->findByName($this->nameGroup); - - // Categories - $categoriesAssociated = $group->categories; - - // Send a notification for each category - foreach ($categoriesAssociated as $category) { - // Category name - $categoryModel = $this->notifynderCategory->findByName($category->name); - - $notification = array_merge( - ['category_id' => $categoryModel->id], - $this->info - ); - - $sender->storeSingle($notification); - } - - return $group; - } -} diff --git a/src/Notifynder/Senders/SendMultiple.php b/src/Notifynder/Senders/SendMultiple.php deleted file mode 100755 index 3fbf974..0000000 --- a/src/Notifynder/Senders/SendMultiple.php +++ /dev/null @@ -1,39 +0,0 @@ -infoNotifications = $infoNotifications; - } - - /** - * Send multiple notifications - * - * @param StoreNotification $sender - * @return mixed - */ - public function send(StoreNotification $sender) - { - return $sender->storeMultiple($this->infoNotifications); - } -} diff --git a/src/Notifynder/Senders/SendOne.php b/src/Notifynder/Senders/SendOne.php deleted file mode 100755 index e06a3aa..0000000 --- a/src/Notifynder/Senders/SendOne.php +++ /dev/null @@ -1,61 +0,0 @@ -infoNotification = $infoNotification; - } - - /** - * Send Single notification - * - * @param StoreNotification $sender - * @return mixed - */ - public function send(StoreNotification $sender) - { - $this->hasCategory(); - - return $sender->storeSingle($this->infoNotification); - } - - /** - * Check if the category of the notification has been - * specified in the array of information - * - * @return bool - * @throws \Fenos\Notifynder\Exceptions\CategoryNotFoundException - */ - protected function hasCategory() - { - if (! array_key_exists('category_id', $this->infoNotification)) { - $error = "Category not found please provide one, - you can not store a notification without category id"; - - throw new CategoryNotFoundException($error); - } - - return true; - } -} diff --git a/src/Notifynder/Senders/SenderFactory.php b/src/Notifynder/Senders/SenderFactory.php deleted file mode 100755 index 4cb5b86..0000000 --- a/src/Notifynder/Senders/SenderFactory.php +++ /dev/null @@ -1,125 +0,0 @@ -notifynderGroup = $notifynderGroup; - $this->notifynderCategory = $notifynderCategory; - } - - /** - * Get the right sender when the data is - * passed - * - * @param array $infoNotifications - * @param $category - * @return SendMultiple|SendOne - */ - public function getSender($infoNotifications, $category = null) - { - if ($infoNotifications instanceof NotifynderBuilder) - { - $infoNotifications = $infoNotifications->toArray(); - } - - // if the array is multidimesional - // it means that we want to send - // multiple notifications - if ($this->isMultiArray($infoNotifications)) - { - return $this->sendMultiple($infoNotifications); - } - else - { - return $this->sendSingle($infoNotifications, $category); - } - } - - /** - * Send Single Notification Sender - * - * @param array $infoNotifications - * @param $category - * @return SendOne - */ - public function sendSingle(array $infoNotifications, $category) - { - return new SendOne($infoNotifications, $category); - } - - /** - * Send Multiple Notification Sender - * - * @param array $infoNotifications - * @return SendMultiple - */ - public function sendMultiple(array $infoNotifications) - { - return new SendMultiple($infoNotifications); - } - - /** - * Get the the send group instance - * - * @param string $group_name - * @param array | \Closure $info - * @return SendGroup - */ - public function sendGroup($group_name, array $info) - { - return new SendGroup( - $this->notifynderGroup, - $this->notifynderCategory, - $group_name, - $info - ); - } - - /** - * Check if the array passed is - * multidimensional - * - * @param $arr - * @return bool - */ - protected function isMultiArray(array $arr) - { - $rv = array_filter($arr, 'is_array'); - if (count($rv) > 0) { - return true; - } - - return false; - } -} diff --git a/src/Notifynder/Senders/SenderManager.php b/src/Notifynder/Senders/SenderManager.php deleted file mode 100755 index 765e13b..0000000 --- a/src/Notifynder/Senders/SenderManager.php +++ /dev/null @@ -1,202 +0,0 @@ -senderFactory = $senderFactory; - $this->storeNotification = $storeNotification; - $this->container = $container; - } - - /** - * Send any notifications - * - * @param array $info - * @param null $category - * @return mixed - */ - public function send($info, $category = null) - { - return $this->sendNow($info, $category); - } - - /** - * Send now whatever data passed - * - * @param array $info - * @param $category - * @return mixed - */ - public function sendNow($info, $category = null) - { - $sender = $this->senderFactory->getSender($info, $category); - - return $sender->send($this->storeNotification); - } - - /** - * Send one method to get fully working - * older version - * - * @param $info - * @param $category - * @return SendOne - */ - public function sendOne($info, $category = null) - { - return $this->senderFactory->sendSingle($info, $category) - ->send($this->storeNotification, $category); - } - - /** - * Send Multiple method to get fully working - * older version - * - * @param $info - * @return SendMultiple - */ - public function sendMultiple($info) - { - return $this->senderFactory->sendMultiple($info) - ->send($this->storeNotification); - } - - /** - * Send a group of notifications - * at once - * - * @param $group_name - * @param array $info - * @return mixed - */ - public function sendGroup($group_name, $info = []) - { - return $this->senderFactory->sendGroup( - $group_name, - $info - )->send($this->storeNotification); - } - - /** - * This method allow to Extend - * notifynder with custom sender - * - * @param $name - * @param callable $extendSender - * @return $this - */ - public function extend($name, $extendSender) - { - $this->senders[$name] = $extendSender; - - return $this; - } - - /** - * Call a custom method - * - * @param $customMethod - * @param $notification - * @return mixed - */ - public function customSender($customMethod,$notification) - { - if (array_key_exists($customMethod, $this->senders)) { - - // get the extended method - $extendedSender = $this->senders[$customMethod]; - - // If is a closure means that i'll return an instance - // with the - if ($extendedSender instanceof Closure) { - - // I invoke the closue expecting an Instance of a custorm - // Sender - $invoker = call_user_func_array($extendedSender, [$notification,$this->container]); - - // If the invoker is a custom sender - // then I invoke it passing the sender class - if ($invoker instanceof Sender) { - - return $invoker->send($this); - } - - // If the dev is attemping to create a custom - // way of storing notifications then - // i'll pass the storenotification contract - if ($invoker instanceof DefaultSender) { - - return $invoker->send($this->storeNotification); - } - } - - $error = "The extention must be an instance of Closure"; - throw new LogicException($error); - } - - $error = "The method $customMethod does not exists on the class ".get_class($this); - throw new BadMethodCallException($error); - } - - /** - * When calling a not existing method - * try to resolve with an exteded - * - * @param $name - * @param $arguments - * @return mixed - */ - function __call($name, $arguments) - { - if (isset($arguments[0])) { - return $this->customSender($name,$arguments[0]); - } - - $error = "No argument passed to the custom sender, - please provide notifications array"; - throw new BadMethodCallException($error); - } -} diff --git a/src/Notifynder/Senders/SingleSender.php b/src/Notifynder/Senders/SingleSender.php new file mode 100644 index 0000000..7e3b17b --- /dev/null +++ b/src/Notifynder/Senders/SingleSender.php @@ -0,0 +1,43 @@ +notification = array_values($notifications)[0]; + } + + /** + * Send the single notification. + * + * @param SenderManagerContract $sender + * @return bool + */ + public function send(SenderManagerContract $sender) + { + $model = notifynder_config()->getNotificationModel(); + + $notification = new $model($this->notification); + + return $notification->save(); + } +} diff --git a/src/Notifynder/Traits/Notifable.php b/src/Notifynder/Traits/Notifable.php new file mode 100755 index 0000000..ddfdc69 --- /dev/null +++ b/src/Notifynder/Traits/Notifable.php @@ -0,0 +1,36 @@ +getNotificationModel(); + if (notifynder_config()->isPolymorphic()) { + return $this->morphMany($model, 'to'); + } + + return $this->hasMany($model, 'to_id'); + } + + /** + * Get the notifications Relationship. + * + * @return \Illuminate\Database\Eloquent\Relations\HasMany|\Illuminate\Database\Eloquent\Relations\MorphMany + */ + public function getNotificationRelation() + { + return $this->notifications(); + } +} diff --git a/src/Notifynder/Traits/NotifableBasic.php b/src/Notifynder/Traits/NotifableBasic.php new file mode 100755 index 0000000..c0b951a --- /dev/null +++ b/src/Notifynder/Traits/NotifableBasic.php @@ -0,0 +1,142 @@ +category($category); + } + + /** + * Get a new NotifynderManager instance with the given category and $this as the sender. + * + * @param string|int|\Fenos\Notifynder\Models\NotificationCategory $category + * @return \Fenos\Notifynder\Managers\NotifynderManager + */ + public function sendNotificationFrom($category) + { + return $this->notifynder($category)->from($this); + } + + /** + * Get a new NotifynderManager instance with the given category and $this as the receiver. + * + * @param string|int|\Fenos\Notifynder\Models\NotificationCategory $category + * @return \Fenos\Notifynder\Managers\NotifynderManager + */ + public function sendNotificationTo($category) + { + return $this->notifynder($category)->to($this); + } + + /** + * Read a single Notification. + * + * @param int $notification + * @return bool + */ + public function readNotification($notification) + { + return $this->updateSingleReadStatus($notification, 1); + } + + /** + * Unread a single Notification. + * + * @param int $notification + * @return bool + */ + public function unreadNotification($notification) + { + return $this->updateSingleReadStatus($notification, 0); + } + + /** + * @param int $notification + * @param int $value + * @return bool + */ + protected function updateSingleReadStatus($notification, $value) + { + if (! TypeChecker::isNotification($notification, false)) { + $notification = $this->getNotificationRelation()->findOrFail($notification); + } + + if ($this->getNotificationRelation()->where($notification->getKeyName(), $notification->getKey())->exists()) { + if ($value) { + return $notification->read(); + } else { + return $notification->unread(); + } + } + + return false; + } + + /** + * Read all Notifications. + * + * @return mixed + */ + public function readAllNotifications() + { + return $this->getNotificationRelation()->update(['read' => 1]); + } + + /** + * Unread all Notifications. + * + * @return mixed + */ + public function unreadAllNotifications() + { + return $this->getNotificationRelation()->update(['read' => 0]); + } + + /** + * Count unread notifications. + * + * @return int + */ + public function countUnreadNotifications() + { + return $this->getNotificationRelation()->byRead(0)->count(); + } + + /** + * Get all Notifications ordered by creation and optional limit. + * + * @param null|int $limit + * @param string $order + * @return \Illuminate\Database\Eloquent\Collection + */ + public function getNotifications($limit = null, $order = 'desc') + { + $query = $this->getNotificationRelation()->orderBy('created_at', $order); + if (! is_null($limit)) { + $query->limit($limit); + } + + return $query->get(); + } +} diff --git a/src/Notifynder/Traits/NotifableLaravel53.php b/src/Notifynder/Traits/NotifableLaravel53.php new file mode 100755 index 0000000..707f78e --- /dev/null +++ b/src/Notifynder/Traits/NotifableLaravel53.php @@ -0,0 +1,36 @@ +getNotificationModel(); + if (notifynder_config()->isPolymorphic()) { + return $this->morphMany($model, 'to'); + } + + return $this->hasMany($model, 'to_id'); + } + + /** + * Get the notifications Relationship. + * + * @return \Illuminate\Database\Eloquent\Relations\HasMany|\Illuminate\Database\Eloquent\Relations\MorphMany + */ + public function getNotificationRelation() + { + return $this->notifynderNotifications(); + } +} diff --git a/src/Notifynder/Translator/Compiler.php b/src/Notifynder/Translator/Compiler.php deleted file mode 100755 index e4a2084..0000000 --- a/src/Notifynder/Translator/Compiler.php +++ /dev/null @@ -1,98 +0,0 @@ -files = $files; - } - - /** - * Get cached file - * - * @return string - */ - public function getFilePath() - { - return $this->getCompiledPath('notification_categories'); - } - - /** - * Get the path to the compiled version of a view. - * - * @param string $filename - * @return string - */ - public function getCompiledPath($filename) - { - return $this->cachePath().'/'.md5($filename); - } - - /** - * Determine if the view at the given path is expired. - * - * @return bool - */ - public function isExpired() - { - $compiled = $this->getFilePath(); - - // If the compiled file doesn't exist we will indicate that the view is expired - // so that it can be re-compiled. Else, we will verify the last modification - // of the views is less than the modification times of the compiled views. - if (! $this->cachePath() || ! $this->files->exists($compiled)) { - return true; - } - - $lastModified = $this->files->lastModified($this->getFilePath()); - - return $lastModified >= $this->files->lastModified($compiled); - } - - /** - * Get cache path - * - * @return string - */ - protected function cachePath() - { - return storage_path('app/notifynder'); - } - - /** - * Cache the file in json format - * - * @param array $contents - * @return bool|int - */ - public function cacheFile(array $contents) - { - $contents = json_encode($contents); - - return $this->files->put($this->getFilePath(), $contents); - } -} diff --git a/src/Notifynder/Translator/TranslatorManager.php b/src/Notifynder/Translator/TranslatorManager.php deleted file mode 100755 index dc57c5c..0000000 --- a/src/Notifynder/Translator/TranslatorManager.php +++ /dev/null @@ -1,134 +0,0 @@ - [ - * 'name.category' => 'text to {parse value} translate' - * ] - * ] - * - * @package Fenos\Notifynder\Translator - */ -class TranslatorManager implements NotifynderTranslator -{ - - /** - * @var Compiler - */ - protected $compiler; - - /** - * @var Repository - */ - private $config; - - /** - * @param Compiler $compiler - * @param Repository $config - */ - public function __construct(Compiler $compiler, Repository $config) - { - $this->compiler = $compiler; - $this->config = $config; - } - - /** - * Translate the given category - * - * @param $language - * @param $nameCategory - * @return mixed - * @throws NotificationLanguageNotFoundException - * @throws NotificationTranslationNotFoundException - */ - public function translate($language, $nameCategory) - { - $translations = $this->getLanguage($language); - - if (array_key_exists($nameCategory, $translations)) { - return $translations[$nameCategory]; - } - - $error = "Translation not found"; - throw new NotificationTranslationNotFoundException($error); - } - - /** - * Get selected language of tranlsations - * - * @param $language - * @return mixed - * @throws NotificationLanguageNotFoundException - */ - public function getLanguage($language) - { - $translations = $this->getTranslations(); - - if (array_key_exists($language, $translations)) { - return $translations[$language]; - } - - $error = "Language Not Found"; - throw new NotificationLanguageNotFoundException($error); - } - - /** - * Get translations - * - * @return array|mixed - */ - public function getTranslations() - { - // File cached path - $filePath = $this->compiler->getFilePath(); - - // If the file exists - if (file_exists($filePath)) { - // Check if is not expired - if (! $this->compiler->isExpired()) { - // Return the cached file in - // an array - return json_decode( - file_get_contents($filePath) - ); - } - } - - return $this->cacheFromConfig(); - } - - /** - * Get the translations from the - * array of the config file and it - * will cache them - * - * @return array - */ - protected function cacheFromConfig() - { - // If is expire then I retrieve directly the array - $fileTranslation = $this->config->get( - 'notifynder.translations' - ); - - // I put the edited content in the cached file - $this->compiler->cacheFile($fileTranslation); - - // return the traslations - return $fileTranslation; - } -} diff --git a/src/config/notifynder.php b/src/config/notifynder.php index 5d6702f..f908d21 100755 --- a/src/config/notifynder.php +++ b/src/config/notifynder.php @@ -8,28 +8,38 @@ return [ - /** + /* * If you have a different user model * please specific it here, this option is not * considerate if using notifynder as polymorphic */ 'model' => 'App\User', - /** + /* * Do you want have notifynder that work polymorphically? * just swap the value to true and you will able to use it! */ 'polymorphic' => false, - /** + /* * If you need to extend the model class of * Notifynder you just need to change this line * With the path / NameSpace of your model and extend it * with Fenos\Notifynder\Models\Notification */ - 'notification_model' => 'Fenos\Notifynder\Models\Notification', + 'notification_model' => \Fenos\Notifynder\Models\Notification::class, - /** + /* + * Coordinating a lots notifications that require extra params + * might cause to forget and not insert the {extra.*} value needed. + * This flag allow you to cause an exception to be thrown if you miss + * to store a extra param that the category will need. + * NOTE: use only in development. + * WHEN DISABLED: will just remove the {extra.*} markup from the sentence + */ + 'strict_extra' => false, + + /* * If you wish to have the translations in a specific file * just require the file on the following option. * @@ -37,7 +47,25 @@ * the language you wish to translate ex 'it' or 'italian' and pass as * value an array with the translations */ - 'translations' => [ + 'translation' => [ + 'enabled' => false, + 'domain' => 'notifynder', + ], + + /* + * If you have added your own fields to the Notification Model + * you can add them to the arrays below. + * + * If you want them to be required by the builder add them to the + * to the required key - if they are just added you can add them + * to the fillable key. + */ + 'additional_fields' => [ + 'required' => [ + + ], + 'fillable' => [ + ], ], ]; diff --git a/src/migrations/2014_02_10_145728_notification_categories.php b/src/migrations/2014_02_10_145728_notification_categories.php index 092c54f..0096cb7 100755 --- a/src/migrations/2014_02_10_145728_notification_categories.php +++ b/src/migrations/2014_02_10_145728_notification_categories.php @@ -5,10 +5,9 @@ class NotificationCategories extends Migration { - /** * Run the migrations. - * + * @return void */ public function up() @@ -27,6 +26,6 @@ public function up() */ public function down() { - Schema::drop('notification_categories'); + Schema::dropIfExists('notification_categories'); } } diff --git a/src/migrations/2014_08_01_210813_create_notification_groups_table.php b/src/migrations/2014_08_01_210813_create_notification_groups_table.php index 47ea82e..e0bed21 100755 --- a/src/migrations/2014_08_01_210813_create_notification_groups_table.php +++ b/src/migrations/2014_08_01_210813_create_notification_groups_table.php @@ -5,7 +5,6 @@ class CreateNotificationGroupsTable extends Migration { - /** * Run the migrations. * @@ -26,6 +25,6 @@ public function up() */ public function down() { - Schema::drop('notification_groups'); + Schema::dropIfExists('notification_groups'); } } diff --git a/src/migrations/2014_08_01_211045_create_notification_category_notification_group_table.php b/src/migrations/2014_08_01_211045_create_notification_category_notification_group_table.php index cd0ebb5..5475c63 100755 --- a/src/migrations/2014_08_01_211045_create_notification_category_notification_group_table.php +++ b/src/migrations/2014_08_01_211045_create_notification_category_notification_group_table.php @@ -5,7 +5,6 @@ class CreateNotificationCategoryNotificationGroupTable extends Migration { - /** * Run the migrations. * @@ -29,6 +28,6 @@ public function up() */ public function down() { - Schema::drop('notifications_categories_in_groups'); + Schema::dropIfExists('notifications_categories_in_groups'); } } diff --git a/src/migrations/2015_05_05_212549_create_notifications_table.php b/src/migrations/2015_05_05_212549_create_notifications_table.php index d9a4339..76e4638 100755 --- a/src/migrations/2015_05_05_212549_create_notifications_table.php +++ b/src/migrations/2015_05_05_212549_create_notifications_table.php @@ -5,7 +5,6 @@ class CreateNotificationsTable extends Migration { - /** * Run the migrations. * @@ -37,6 +36,6 @@ public function up() */ public function down() { - Schema::drop('notifications'); + Schema::dropIfExists('notifications'); } } diff --git a/src/migrations/2015_06_06_211555_add_expire_time_column_to_notification_table.php b/src/migrations/2015_06_06_211555_add_expire_time_column_to_notification_table.php index 611073c..3382315 100755 --- a/src/migrations/2015_06_06_211555_add_expire_time_column_to_notification_table.php +++ b/src/migrations/2015_06_06_211555_add_expire_time_column_to_notification_table.php @@ -4,7 +4,6 @@ class AddExpireTimeColumnToNotificationTable extends Migration { - /** * Run the migrations. * diff --git a/src/migrations/2015_06_06_211555_change_type_to_extra_in_notifications_table.php b/src/migrations/2015_06_06_211555_change_type_to_extra_in_notifications_table.php index c41d245..646e638 100755 --- a/src/migrations/2015_06_06_211555_change_type_to_extra_in_notifications_table.php +++ b/src/migrations/2015_06_06_211555_change_type_to_extra_in_notifications_table.php @@ -4,7 +4,6 @@ class ChangeTypeToExtraInNotificationsTable extends Migration { - /** * Run the migrations. * @@ -15,12 +14,9 @@ public function up() Schema::table('notifications', function ($table) { $driver = Config::get('database.driver'); - if ($driver === 'mysql' || $driver === 'sqlite') - { + if ($driver === 'mysql' || $driver === 'sqlite') { DB::statement('ALTER TABLE notifications MODIFY COLUMN extra json'); - } - elseif ($driver === 'pgsql') - { + } elseif ($driver === 'pgsql') { DB::statement('ALTER TABLE notifications ALTER COLUMN extra TYPE json USING code::string'); } }); @@ -34,15 +30,11 @@ public function up() public function down() { Schema::table('notifications', function ($table) { - $driver = Config::get('database.driver'); - if ($driver === 'mysql' || $driver === 'sqlite') - { + if ($driver === 'mysql' || $driver === 'sqlite') { DB::statement('ALTER TABLE notifications MODIFY COLUMN extra STRING(255)'); - } - elseif ($driver === 'pgsql') - { + } elseif ($driver === 'pgsql') { DB::statement('ALTER TABLE notifications ALTER COLUMN extra TYPE string USING code::json'); } }); diff --git a/src/migrations/2015_06_07_211555_alter_category_name_to_unique.php b/src/migrations/2015_06_07_211555_alter_category_name_to_unique.php index c1ddd18..cfbc7a9 100755 --- a/src/migrations/2015_06_07_211555_alter_category_name_to_unique.php +++ b/src/migrations/2015_06_07_211555_alter_category_name_to_unique.php @@ -4,7 +4,6 @@ class AlterCategoryNameToUnique extends Migration { - /** * Run the migrations. * diff --git a/src/migrations/2016_04_19_200827_make_notification_url_nullable.php b/src/migrations/2016_04_19_200827_make_notification_url_nullable.php new file mode 100644 index 0000000..209686d --- /dev/null +++ b/src/migrations/2016_04_19_200827_make_notification_url_nullable.php @@ -0,0 +1,31 @@ +string('url')->nullable()->change(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('notifications', function (Blueprint $table) { + $table->string('url')->change(); + }); + } +} diff --git a/src/migrations/2016_05_19_144531_add_stack_id_to_notifications.php b/src/migrations/2016_05_19_144531_add_stack_id_to_notifications.php new file mode 100644 index 0000000..0d0a413 --- /dev/null +++ b/src/migrations/2016_05_19_144531_add_stack_id_to_notifications.php @@ -0,0 +1,31 @@ +integer('stack_id')->unsigned()->nullable()->after('expire_time'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('notifications', function (Blueprint $table) { + $table->dropColumn('stack_id'); + }); + } +} diff --git a/src/migrations/2016_07_01_153156_update_version4_notifications_table.php b/src/migrations/2016_07_01_153156_update_version4_notifications_table.php new file mode 100644 index 0000000..119a262 --- /dev/null +++ b/src/migrations/2016_07_01_153156_update_version4_notifications_table.php @@ -0,0 +1,37 @@ +bigInteger('from_id')->unsigned()->nullable()->change(); + }); + Schema::table('notifications', function (Blueprint $table) { + $table->renameColumn('expire_time', 'expires_at'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('notifications', function (Blueprint $table) { + $table->renameColumn('expires_at', 'expire_time'); + }); + Schema::table('notifications', function (Blueprint $table) { + $table->bigInteger('from_id')->unsigned()->change(); + }); + } +} diff --git a/src/migrations/2016_11_02_193415_drop_version4_unused_tables.php b/src/migrations/2016_11_02_193415_drop_version4_unused_tables.php new file mode 100644 index 0000000..b0af3a7 --- /dev/null +++ b/src/migrations/2016_11_02_193415_drop_version4_unused_tables.php @@ -0,0 +1,27 @@ + NotifynderFacade::class, + ]; + } + + public function setUp() + { + parent::setUp(); + // This should only do work for Sqlite DBs in memory. + $artisan = $this->app->make('Illuminate\Contracts\Console\Kernel'); + app('db')->beginTransaction(); + $this->migrate($artisan); + $this->migrate($artisan, '/../../../../tests/migrations'); + // Set up the User Test Model + app('config')->set('notifynder.notification_model', 'Fenos\Notifynder\Models\Notification'); + app('config')->set('notifynder.model', 'Fenos\Tests\Models\User'); + } + + protected function getEnvironmentSetUp($app) + { + $app['config']->set('database.default', 'testbench'); + $app['config']->set('database.connections.testbench', [ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'prefix' => '', + ]); + } + + public function tearDown() + { + app('db')->rollback(); + } + + protected function getApplicationTimezone($app) + { + return 'UTC'; + } + + protected function migrate($artisan, $path = '/../../../../src/migrations') + { + $artisan->call('migrate', [ + '--database' => 'testbench', + '--path' => $path, + ]); + } + + protected function createCategory(array $attributes = []) + { + $attributes = array_merge([ + 'text' => 'Notification send from #{from.id} to #{to.id}.', + 'name' => 'test.category', + ], $attributes); + + return NotificationCategory::create($attributes); + } + + protected function createUser(array $attributes = []) + { + $attributes = array_merge([ + 'firstname' => 'John', + 'lastname' => 'Doe', + ], $attributes); + + if ($this->getLaravelVersion() < 5.3) { + return User::create($attributes); + } else { + return UserL53::create($attributes); + } + } + + protected function createCar(array $attributes = []) + { + $attributes = array_merge([ + 'brand' => 'Audi', + 'model' => 'A6', + ], $attributes); + + if ($this->getLaravelVersion() < 5.3) { + return Car::create($attributes); + } else { + return CarL53::create($attributes); + } + } + + protected function sendNotificationTo(Model $model) + { + return $model + ->sendNotificationTo(1) + ->from(2) + ->send(); + } + + protected function sendNotificationsTo(Model $model, $amount = 10) + { + while ($amount > 0) { + $this->sendNotificationTo($model); + $amount--; + } + } + + protected function getLaravelVersion() + { + $version = app()->version(); + $parts = explode('.', $version); + + return ($parts[0].'.'.$parts[1]) * 1; + } +} diff --git a/tests/TestCaseDB.php b/tests/TestCaseDB.php deleted file mode 100755 index c8dbb2a..0000000 --- a/tests/TestCaseDB.php +++ /dev/null @@ -1,88 +0,0 @@ -app->make('Illuminate\Contracts\Console\Kernel'); - - app('db')->beginTransaction(); - - $this->migrate($artisan); - $this->migrate($artisan,'/../../../../tests/migrations'); - - // Set up the User Test Model - app('config')->set('notifynder.notification_model','Fenos\Notifynder\Models\Notification'); - app('config')->set('notifynder.model','Fenos\Tests\Models\User'); - - } - - /** - * Define environment setup. - * - * @param \Illuminate\Foundation\Application $app - * @return void - */ - protected function getEnvironmentSetUp($app) - { - $app['config']->set('database.default', 'testbench'); - $app['config']->set('database.connections.testbench', array( - 'driver' => 'sqlite', - 'database' => ':memory:', - 'prefix' => '', - )); - } - - /** - * Rollback transactions after each test. - */ - public function tearDown() - { - app('db')->rollback(); - } - - /** - * Get application timezone. - * - * @param \Illuminate\Foundation\Application $app - * @return string|null - */ - protected function getApplicationTimezone($app) - { - return 'UTC'; - } - - /** - * Migrate the migrations files - * - * @param $artisan - * @param string $path - */ - private function migrate($artisan,$path = '/../../../../src/migrations') - { - $artisan->call('migrate', [ - '--database' => 'testbench', - '--path' => $path - ]); - } -} \ No newline at end of file diff --git a/tests/factories/factories.php b/tests/factories/factories.php deleted file mode 100755 index 84fffdb..0000000 --- a/tests/factories/factories.php +++ /dev/null @@ -1,33 +0,0 @@ - $faker->name, - 'text' => 'test notification' -]); - - -$factory('Fenos\Tests\Models\User',[ - - 'name' => $faker->name, - 'surname' => $faker->lastName -]); - -$factory('Fenos\Notifynder\Models\Notification',[ - - 'from_id' => 'factory:Fenos\Tests\Models\User', - 'from_type' => 'Fenos\Tests\Models\User', - 'to_id' => 'factory:Fenos\Tests\Models\User', - 'to_type' => 'Fenos\Tests\Models\User', - 'category_id' => 'factory:Fenos\Notifynder\Models\NotificationCategory', - 'url' => $faker->url, - 'extra' => $faker->name, - 'read' => 0, - 'expire_time' => null, - 'created_at' => $faker->dateTime, - 'updated_at' => $faker->dateTime, -]); - -$factory('Fenos\Notifynder\Models\NotificationGroup',[ - 'name' => $faker->name, -]); \ No newline at end of file diff --git a/tests/integration/Builder/BuilderNotificationTest.php b/tests/integration/Builder/BuilderNotificationTest.php new file mode 100644 index 0000000..92229e6 --- /dev/null +++ b/tests/integration/Builder/BuilderNotificationTest.php @@ -0,0 +1,79 @@ +set('foo', 'bar'); + + $this->assertInternalType('array', $notification->attributes()); + $this->assertCount(1, $notification->attributes()); + $this->assertArrayHasKey('foo', $notification->attributes()); + $this->assertTrue($notification->has('foo')); + $this->assertSame('bar', $notification->attribute('foo')); + $this->assertFalse($notification->isValid()); + + $notification->set('category_id', 1); + $notification->set('from_id', 1); + $notification->set('to_id', 2); + + $this->assertTrue($notification->isValid()); + } + + public function testTypeChanger() + { + $notification = new Notification(); + $notification->set('category_id', 1); + $notification->set('from_id', 1); + $notification->set('to_id', 2); + $notification->set('extra', ['foo' => 'bar']); + + $this->assertTrue($notification->isValid()); + $this->assertInternalType('array', $notification->toArray()); + $this->assertInternalType('array', $notification->toArray()['extra']); + $this->assertInternalType('array', $notification->toDbArray()); + $this->assertInternalType('string', $notification->toDbArray()['extra']); + $this->assertJson($notification->toJson()); + $this->assertInternalType('string', $notification->toString()); + $this->assertInternalType('string', (string) $notification); + } + + public function testOverloaded() + { + $notification = new Notification(); + $notification->category_id = 1; + $notification->from_id = 1; + $notification->to_id = 2; + + $this->assertTrue($notification->isValid()); + $this->assertSame(1, $notification->category_id); + $this->assertSame(1, $notification->from_id); + $this->assertSame(2, $notification->to_id); + } + + public function testOffsetMethods() + { + $notification = new Notification(); + $notification->offsetSet('foo', 'bar'); + $this->assertTrue($notification->offsetExists('foo')); + $this->assertSame('bar', $notification->offsetGet('foo')); + $notification->offsetUnset('foo'); + $this->assertFalse($notification->offsetExists('foo')); + } + + public function testGetText() + { + $category = $this->createCategory(); + $from = $this->createUser(); + $to = $this->createUser(); + $notification = new Notification(); + $notification->set('category_id', $category->getKey()); + $notification->set('from_id', $from->getKey()); + $notification->set('to_id', $to->getKey()); + + $this->assertSame('Notification send from #1 to #2.', $notification->getText()); + } +} diff --git a/tests/integration/Builder/BuilderTest.php b/tests/integration/Builder/BuilderTest.php new file mode 100644 index 0000000..04c5a2f --- /dev/null +++ b/tests/integration/Builder/BuilderTest.php @@ -0,0 +1,282 @@ +category(1) + ->from(1) + ->to(2) + ->getNotification(); + + $this->assertInstanceOf(Notification::class, $notification); + + $this->assertSame(1, $notification->category_id); + $this->assertSame(1, $notification->from_id); + $this->assertSame('Fenos\Tests\Models\User', $notification->from_type); + $this->assertSame(2, $notification->to_id); + $this->assertSame('Fenos\Tests\Models\User', $notification->to_type); + $this->assertInstanceOf(Carbon::class, $notification->created_at); + $this->assertInstanceOf(Carbon::class, $notification->updated_at); + } + + public function testCreateSingleAnonymousNotification() + { + $builder = new Builder(); + $notification = $builder + ->category(1) + ->anonymous() + ->to(2) + ->getNotification(); + + $this->assertInstanceOf(Notification::class, $notification); + + $this->assertSame(1, $notification->category_id); + $this->assertNull($notification->from_id); + $this->assertNull($notification->from_type); + $this->assertSame(2, $notification->to_id); + $this->assertSame('Fenos\Tests\Models\User', $notification->to_type); + $this->assertInstanceOf(Carbon::class, $notification->created_at); + $this->assertInstanceOf(Carbon::class, $notification->updated_at); + } + + public function testCreateSingleNotificationWithAll() + { + $builder = new Builder(); + $notification = $builder + ->category(1) + ->from(1) + ->to(2) + ->url('http://notifynder.info') + ->extra([ + 'foo' => 'bar', + ]) + ->expire(Carbon::tomorrow()) + ->getNotification(); + + $this->assertInstanceOf(Notification::class, $notification); + + $this->assertSame('http://notifynder.info', $notification->url); + $this->assertInternalType('array', $notification->extra); + $this->assertCount(1, $notification->extra); + $this->assertSame('bar', $notification->extra['foo']); + $this->assertInstanceOf(Carbon::class, $notification->expires_at); + } + + public function testCreateSingleNotificationWithExtendedExtra() + { + $builder = new Builder(); + $notification = $builder + ->category(1) + ->from(1) + ->to(2) + ->extra([ + 'foo' => 'bar', + ], false) + ->extra([ + 'hello' => 'world', + ], false) + ->getNotification(); + + $this->assertInstanceOf(Notification::class, $notification); + + $this->assertInternalType('array', $notification->extra); + $this->assertCount(2, $notification->extra); + $this->assertSame('bar', $notification->extra['foo']); + $this->assertSame('world', $notification->extra['hello']); + } + + public function testCreateSingleNotificationWithOverriddenExtra() + { + $builder = new Builder(); + $notification = $builder + ->category(1) + ->from(1) + ->to(2) + ->extra([ + 'foo' => 'bar', + ], true) + ->extra([ + 'hello' => 'world', + ], true) + ->getNotification(); + + $this->assertInstanceOf(Notification::class, $notification); + + $this->assertInternalType('array', $notification->extra); + $this->assertCount(1, $notification->extra); + $this->assertSame('world', $notification->extra['hello']); + } + + public function testCreateSingleNotificationAndGetArray() + { + $builder = new Builder(); + $notifications = $builder + ->category(1) + ->from(1) + ->to(2) + ->getNotifications(); + + $this->assertInternalType('array', $notifications); + $this->assertCount(1, $notifications); + + $this->assertInstanceOf(Notification::class, $notifications[0]); + } + + public function testCreateSingleUnvalidNotification() + { + $this->setExpectedException(UnvalidNotificationException::class); + + $builder = new Builder(); + $builder + ->from(1) + ->to(2) + ->getNotification(); + } + + public function testCreateSingleCatchedUnvalidNotificationW() + { + try { + $builder = new Builder(); + $builder + ->from(1) + ->to(2) + ->getNotification(); + } catch (UnvalidNotificationException $e) { + $this->assertInstanceOf(Notification::class, $e->getNotification()); + } + } + + public function testCreateMultipleNotifications() + { + $datas = [2, 3, 4]; + $builder = new Builder(); + $notifications = $builder->loop($datas, function ($builder, $data) { + $builder->category(1) + ->from(1) + ->to($data); + })->getNotifications(); + + $this->assertInternalType('array', $notifications); + $this->assertCount(count($datas), $notifications); + + foreach ($notifications as $index => $notification) { + $this->assertInstanceOf(Notification::class, $notification); + + $this->assertSame(1, $notification->category_id); + $this->assertSame(1, $notification->from_id); + $this->assertSame('Fenos\Tests\Models\User', $notification->from_type); + $this->assertSame($datas[$index], $notification->to_id); + $this->assertSame('Fenos\Tests\Models\User', $notification->to_type); + $this->assertInstanceOf(Carbon::class, $notification->created_at); + $this->assertInstanceOf(Carbon::class, $notification->updated_at); + } + } + + public function testCreateMultipleUnvalidNotifications() + { + $this->setExpectedException(UnvalidNotificationException::class); + + $builder = new Builder(); + $builder->loop([2, 3, 4], function ($builder, $data) { + $builder->category(1) + ->to($data); + })->getNotifications(); + } + + public function testCreateSingleNotificationWithAdditionalField() + { + notifynder_config()->set('additional_fields.fillable', []); + + $builder = new Builder(); + $notification = $builder + ->category(1) + ->from(1) + ->to(2) + ->setField('additional_field', 'value') + ->getNotification(); + + $this->assertInstanceOf(Notification::class, $notification); + $this->assertSame(1, $notification->category_id); + $this->assertNull($notification->additional_field); + + notifynder_config()->set('additional_fields.fillable', ['additional_field']); + + $builder = new Builder(); + $notification = $builder + ->category(1) + ->from(1) + ->to(2) + ->setField('additional_field', 'value') + ->getNotification(); + + $this->assertInstanceOf(Notification::class, $notification); + $this->assertSame(1, $notification->category_id); + $this->assertSame('value', $notification->additional_field); + } + + public function testCreateSingleUnvalidNotificationWithRequiredField() + { + $this->setExpectedException(UnvalidNotificationException::class); + + notifynder_config()->set('additional_fields.required', ['required_field']); + + $builder = new Builder(); + $notification = $builder + ->category(1) + ->from(1) + ->to(2) + ->getNotification(); + } + + public function testCreateSingleNotificationWithRequiredField() + { + notifynder_config()->set('additional_fields.required', ['required_field']); + + $builder = new Builder(); + $notification = $builder + ->category(1) + ->from(1) + ->to(2) + ->setField('required_field', 'value') + ->getNotification(); + + $this->assertInstanceOf(Notification::class, $notification); + $this->assertSame(1, $notification->category_id); + $this->assertSame('value', $notification->required_field); + } + + public function testCreateSingleNotificationWithSplittedEntityData() + { + $builder = new Builder(); + $notification = $builder + ->category(1) + ->from(\Fenos\Tests\Models\User::class, 1) + ->to(\Fenos\Tests\Models\User::class, 2) + ->getNotification(); + + $this->assertInstanceOf(Notification::class, $notification); + $this->assertSame(1, $notification->category_id); + $this->assertSame(1, $notification->from_id); + $this->assertSame(\Fenos\Tests\Models\User::class, $notification->from_type); + $this->assertSame(2, $notification->to_id); + $this->assertSame(\Fenos\Tests\Models\User::class, $notification->to_type); + } + + public function testOffsetMethods() + { + $builder = new Builder(); + $builder->offsetSet('foo', 'bar'); + $this->assertTrue($builder->offsetExists('foo')); + $this->assertSame('bar', $builder->offsetGet('foo')); + $builder->offsetUnset('foo'); + $this->assertFalse($builder->offsetExists('foo')); + } +} diff --git a/tests/integration/Collections/ConfigTest.php b/tests/integration/Collections/ConfigTest.php new file mode 100644 index 0000000..44738af --- /dev/null +++ b/tests/integration/Collections/ConfigTest.php @@ -0,0 +1,111 @@ +assertInternalType('bool', $config->isPolymorphic()); + } + + public function testIsStrict() + { + $config = app('notifynder.config'); + $this->assertInternalType('bool', $config->isStrict()); + } + + public function testIsTranslated() + { + $config = app('notifynder.config'); + $this->assertInternalType('bool', $config->isTranslated()); + } + + public function testGetNotificationModel() + { + $config = app('notifynder.config'); + $this->assertInternalType('string', $config->getNotificationModel()); + $this->assertSame(Notification::class, $config->getNotificationModel()); + } + + public function testGetNotificationModelFallback() + { + $config = app('notifynder.config'); + $config->set('notification_model', 'undefined_class_name'); + $this->assertInternalType('string', $config->getNotificationModel()); + $this->assertSame(Notification::class, $config->getNotificationModel()); + } + + public function testGetNotifiedModel() + { + $config = app('notifynder.config'); + $this->assertInternalType('string', $config->getNotifiedModel()); + $this->assertSame(User::class, $config->getNotifiedModel()); + } + + public function testGetNotifiedModelFail() + { + $this->setExpectedException(InvalidArgumentException::class); + + $config = app('notifynder.config'); + $config->set('model', 'undefined_class_name'); + $config->getNotifiedModel(); + } + + public function testGetAdditionalFields() + { + $config = app('notifynder.config'); + $this->assertInternalType('array', $config->getAdditionalFields()); + $this->assertSame([], $config->getAdditionalFields()); + } + + public function testGetAdditionalRequiredFields() + { + $config = app('notifynder.config'); + $this->assertInternalType('array', $config->getAdditionalRequiredFields()); + $this->assertSame([], $config->getAdditionalRequiredFields()); + } + + public function testGetTranslationDomain() + { + $config = app('notifynder.config'); + $this->assertInternalType('string', $config->getTranslationDomain()); + $this->assertSame('notifynder', $config->getTranslationDomain()); + } + + public function testHasTrue() + { + $config = app('notifynder.config'); + $this->assertTrue($config->has('polymorphic')); + } + + public function testHasFalse() + { + $config = app('notifynder.config'); + $this->assertFalse($config->has('undefined_config_key')); + } + + public function testSet() + { + $config = app('notifynder.config'); + $config->set('polymorphic', true); + $this->assertTrue($config->get('polymorphic')); + } + + public function testGetOverloaded() + { + $config = app('notifynder.config'); + $this->assertInternalType('bool', $config->polymorphic); + } + + public function testSetOverloaded() + { + $config = app('notifynder.config'); + + $config->polymorphic = true; + $this->assertInternalType('bool', $config->polymorphic); + $this->assertTrue($config->get('polymorphic')); + } +} diff --git a/tests/integration/CreateModels.php b/tests/integration/CreateModels.php deleted file mode 100755 index e2eb588..0000000 --- a/tests/integration/CreateModels.php +++ /dev/null @@ -1,67 +0,0 @@ - $this->to['id'], - 'to_type' => $this->to['type'], - 'read' => 0 - ]; - - return Factory::times($this->multiNotificationsNumber) - ->create(Notification::class,array_merge($to_entity,$data)); - } - - /** - * @param array $data - * @return mixed - */ - protected function createUser(array $data = []) - { - return Factory::create('Fenos\Tests\Models\User',$data); - } -} \ No newline at end of file diff --git a/tests/integration/CustomSender.php b/tests/integration/CustomSender.php deleted file mode 100755 index 21eaaa3..0000000 --- a/tests/integration/CustomSender.php +++ /dev/null @@ -1,43 +0,0 @@ -notifications = $notifications; - $this->notifynder = $notifynder; - } - - /** - * Send notification - * - * @param NotifynderSender $sender - * @return mixed - */ - public function send(NotifynderSender $sender) - { -// dd($storeNotification); - return $sender->send($this->notifications); - } -} \ No newline at end of file diff --git a/tests/integration/Facades/NotifynderFacadeTest.php b/tests/integration/Facades/NotifynderFacadeTest.php new file mode 100644 index 0000000..dc53262 --- /dev/null +++ b/tests/integration/Facades/NotifynderFacadeTest.php @@ -0,0 +1,21 @@ +from(1) + ->to(2) + ->send(); + + $this->assertTrue($sent); + + $notifications = ModelNotification::all(); + $this->assertCount(1, $notifications); + $this->assertInstanceOf(EloquentCollection::class, $notifications); + } +} diff --git a/tests/integration/Handler/NotifyEvent.php b/tests/integration/Handler/NotifyEvent.php deleted file mode 100755 index d35abf3..0000000 --- a/tests/integration/Handler/NotifyEvent.php +++ /dev/null @@ -1,31 +0,0 @@ -notifynderEvent = $notifynderEvent; - } - - /** - * @return NotifynderEvent - */ - public function getNotifynderEvent() - { - return $this->notifynderEvent; - } -} \ No newline at end of file diff --git a/tests/integration/Handler/NotifynderHandlerTest.php b/tests/integration/Handler/NotifynderHandlerTest.php deleted file mode 100755 index 155b3e9..0000000 --- a/tests/integration/Handler/NotifynderHandlerTest.php +++ /dev/null @@ -1,185 +0,0 @@ - 'NotifyUserTest' - ]; - - /** - * User to - * - * @var User - */ - protected $to; - - /** - * @var User - */ - protected $from; - - /** - * @var Dispatcher - */ - protected $laravelDispatcher; - - /** - * Listen test listeners - */ - public function setUp() - { - parent::setUp(); - - $this->dispatcher = app('notifynder'); - $this->laravelDispatcher = app('events'); - - // Boot Listeners - $this->dispatcher->bootListeners($this->listeners); - - // Create Users - $this->to = $this->createUser(); - $this->from = $this->createUser(); - - // Create Category - $this->createCategory([ - 'name' => 'activation' - ]); - - $this->createCategory([ - 'name' => 'confirmation' - ]); - } - - /** @test */ - function it_fire_an_event_sending_a_specific_notification_from_the_handler() - { - $this->dispatcher->fire('notify@userActivated','activation'); - - $notification = \Fenos\Notifynder\Models\Notification::all(); - - $this->assertCount(1,$notification); - } - - /** @test */ - function it_fire_an_event_sending_multiple_notifications() - { - $this->dispatcher->fire('notify@userMultiple','activation'); - - $notification = \Fenos\Notifynder\Models\Notification::all(); - - $this->assertCount(2,$notification); - } - - /** @test */ - function it_delete_2_notification_to_be_sent_trought_the_handler() - { - $this->dispatcher->delegate([ - 'activation' => 'notify@userActivated', - 'confirmation' => 'notify@userMultiple' - ]); - - $notification = \Fenos\Notifynder\Models\Notification::all(); - - $this->assertCount(3,$notification); - } - - /** @test */ - function it_trigger_an_handler_using_native_laravel_dispatcher() - { - $testListener = [ - NotifyEvent::class => [ - NotifyUserTest::class - ] - ]; - - // Listen for events as the laravel way - foreach ($testListener as $event => $listeners) - { - foreach ($listeners as $listener) - { - $this->laravelDispatcher->listen($event, $listener); - } - } - - $notification = $this->laravelDispatcher->fire( - new NotifyEvent(new NotifynderEvent('userActivated')) - ); - - $this->assertEquals('hello',$notification[0]->url); - } -} - -/* -|-------------------------------------------------------------------------- -| NotifyUserTest: Example of Handler -|-------------------------------------------------------------------------- -| NotifyUserTest Class is an handler to test the implementation against it ---------------------------------------------------------------------------*/ - -/** - * Class NotifyUserTest - */ -class NotifyUserTest extends NotifynderHandler { - - /** - * Test trigger one notification - * - * @param NotifynderEvent $event - * @param NotifynderManager $notifynder - * @return mixed - * @throws \Fenos\Notifynder\Exceptions\NotificationBuilderException - */ - public function userActivated(NotifynderEvent $event, NotifynderManager $notifynder) - { - return $notifynder->builder() - ->category('activation') - ->url('hello') - ->from(1) - ->to(2); - } - - /** - * Test send multiple notifications from - * the handler - * - * @param NotifynderEvent $event - * @param NotifynderManager $notifynder - * @return $this - */ - public function userMultiple(NotifynderEvent $event, NotifynderManager $notifynder) - { - // Retrieve users - $users = [1,2]; - - return $notifynder->builder()->loop($users,function(NotifynderBuilder $builder,$value,$key) { - - return $builder->category('activation') - ->url('hello') - ->from(1) - ->to($value); - }); - } - -} \ No newline at end of file diff --git a/tests/integration/Helpers/HelpersTest.php b/tests/integration/Helpers/HelpersTest.php new file mode 100644 index 0000000..f46bf21 --- /dev/null +++ b/tests/integration/Helpers/HelpersTest.php @@ -0,0 +1,16 @@ +assertInstanceOf(Config::class, notifynder_config()); + } + + public function testNotifynderConfigGet() + { + $this->assertInternalType('bool', notifynder_config('polymorphic')); + } +} diff --git a/tests/integration/Helpers/TypeCheckerTest.php b/tests/integration/Helpers/TypeCheckerTest.php new file mode 100644 index 0000000..2416b10 --- /dev/null +++ b/tests/integration/Helpers/TypeCheckerTest.php @@ -0,0 +1,103 @@ +assertTrue(TypeChecker::isString('hello world')); + } + + public function testIsStringFailStrict() + { + $this->setExpectedException(InvalidArgumentException::class); + TypeChecker::isString(15); + } + + public function testIsStringFail() + { + $this->assertFalse(TypeChecker::isString(15, false)); + } + + public function testIsNumeric() + { + $this->assertTrue(TypeChecker::isNumeric(15)); + } + + public function testIsNumericFailStrict() + { + $this->setExpectedException(InvalidArgumentException::class); + TypeChecker::isNumeric('hello world'); + } + + public function testIsNumericFail() + { + $this->assertFalse(TypeChecker::isNumeric('hello world', false)); + } + + public function testIsDate() + { + $this->assertTrue(TypeChecker::isDate(Carbon::now())); + } + + public function testIsDateFailStrict() + { + $this->setExpectedException(InvalidArgumentException::class); + TypeChecker::isDate('hello world'); + } + + public function testIsDateFail() + { + $this->assertFalse(TypeChecker::isDate('hello world', false)); + } + + public function testIsArray() + { + $this->assertTrue(TypeChecker::isArray([1, 2, 3])); + } + + public function testIsArrayFailStrict() + { + $this->setExpectedException(InvalidArgumentException::class); + TypeChecker::isArray(collect([1, 2, 3])); + } + + public function testIsArrayFail() + { + $this->assertFalse(TypeChecker::isArray(collect([1, 2, 3]), false)); + } + + public function testIsIterable() + { + $this->assertTrue(TypeChecker::isIterable(collect([1, 2, 3]))); + } + + public function testIsIterableFailStrict() + { + $this->setExpectedException(InvalidArgumentException::class); + TypeChecker::isIterable([]); + } + + public function testIsIterableFail() + { + $this->assertFalse(TypeChecker::isIterable([], false)); + } + + public function testIsNotification() + { + $this->assertTrue(TypeChecker::isNotification(new \Fenos\Notifynder\Models\Notification())); + } + + public function testIsNotificationFailStrict() + { + $this->setExpectedException(InvalidArgumentException::class); + TypeChecker::isNotification([]); + } + + public function testIsNotificationFail() + { + $this->assertFalse(TypeChecker::isNotification([], false)); + } +} diff --git a/tests/integration/Managers/NotifynderManagerTest.php b/tests/integration/Managers/NotifynderManagerTest.php new file mode 100644 index 0000000..dfa8635 --- /dev/null +++ b/tests/integration/Managers/NotifynderManagerTest.php @@ -0,0 +1,197 @@ +setExpectedException(BadMethodCallException::class); + + $manager = app('notifynder'); + $manager->undefinedMethod(); + } + + public function testGetBuilderInstance() + { + $manager = app('notifynder'); + $builder = $manager->builder(); + + $this->assertInstanceOf(Builder::class, $builder); + } + + public function testGetSenderInstance() + { + $manager = app('notifynder'); + $sender = $manager->sender(); + + $this->assertInstanceOf(SenderManager::class, $sender); + } + + public function testBuildSingleNotification() + { + $manager = app('notifynder'); + $notification = $manager->category(1) + ->from(1) + ->to(2) + ->getNotification(); + + $this->assertInstanceOf(BuilderNotification::class, $notification); + } + + public function testBuildMultipleNotifications() + { + $datas = [2, 3, 4]; + $manager = app('notifynder'); + $notifications = $manager->loop($datas, function ($builder, $data) { + $builder->category(1) + ->from(1) + ->to($data); + })->getNotifications(); + + $this->assertInternalType('array', $notifications); + $this->assertCount(count($datas), $notifications); + } + + public function testSendSingleNotification() + { + $manager = app('notifynder'); + $sent = $manager->category(1) + ->from(1) + ->to(2) + ->send(); + + $this->assertTrue($sent); + + $notifications = ModelNotification::all(); + $this->assertCount(1, $notifications); + $this->assertInstanceOf(EloquentCollection::class, $notifications); + } + + public function testSendSingleAnonymousNotification() + { + $manager = app('notifynder'); + $sent = $manager->category(1) + ->anonymous() + ->to(2) + ->send(); + + $this->assertTrue($sent); + + $notifications = ModelNotification::all(); + $this->assertCount(1, $notifications); + $this->assertInstanceOf(EloquentCollection::class, $notifications); + $notification = $notifications->first(); + $this->assertInstanceOf(ModelNotification::class, $notification); + $this->assertNull($notification->from); + $this->assertNull($notification->from_id); + $this->assertNull($notification->from_type); + $this->assertTrue($notification->isAnonymous()); + } + + public function testSendMultipleNotifications() + { + $datas = [2, 3, 4]; + $manager = app('notifynder'); + $sent = $manager->loop($datas, function ($builder, $data) { + $builder->category(1) + ->from(1) + ->to($data); + })->send(); + + $this->assertTrue($sent); + + $notifications = ModelNotification::all(); + $this->assertCount(count($datas), $notifications); + $this->assertInstanceOf(EloquentCollection::class, $notifications); + } + + public function testSendSingleSpecificNotification() + { + $manager = app('notifynder'); + $sent = $manager->category(1) + ->from(1) + ->to(2) + ->sendSingle(); + + $this->assertTrue($sent); + + $notifications = ModelNotification::all(); + $this->assertCount(1, $notifications); + $this->assertInstanceOf(EloquentCollection::class, $notifications); + } + + public function testSendOnceSameNotifications() + { + $manager = app('notifynder'); + $sent = $manager->category(1) + ->from(1) + ->to(2) + ->extra(['foo' => 'bar']) + ->sendOnce(); + $this->assertTrue($sent); + + $notifications = ModelNotification::all(); + $this->assertCount(1, $notifications); + $this->assertInstanceOf(EloquentCollection::class, $notifications); + $notificationFirst = $notifications->first(); + $this->assertInstanceOf(Notification::class, $notificationFirst); + + $this->assertEquals(0, $notificationFirst->read); + $notificationFirst->read(); + $this->assertEquals(1, $notificationFirst->read); + + sleep(1); + + $sent = $manager->category(1) + ->from(1) + ->to(2) + ->extra(['foo' => 'bar']) + ->sendOnce(); + $this->assertTrue($sent); + + $notifications = ModelNotification::all(); + $this->assertCount(1, $notifications); + $this->assertInstanceOf(EloquentCollection::class, $notifications); + $notificationSecond = $notifications->first(); + $this->assertInstanceOf(Notification::class, $notificationSecond); + + $this->assertEquals(0, $notificationSecond->read); + + $this->assertSame($notificationFirst->getKey(), $notificationSecond->getKey()); + $this->assertEquals($notificationFirst->created_at, $notificationSecond->created_at); + $diff = $notificationFirst->updated_at->diffInSeconds($notificationSecond->updated_at); + $this->assertGreaterThan(0, $diff); + } + + public function testSendOnceDifferentNotifications() + { + $manager = app('notifynder'); + $sent = $manager->category(1) + ->from(1) + ->to(2) + ->extra(['foo' => 'bar']) + ->sendOnce(); + $this->assertTrue($sent); + + $notifications = ModelNotification::all(); + $this->assertCount(1, $notifications); + $this->assertInstanceOf(EloquentCollection::class, $notifications); + + $sent = $manager->category(1) + ->from(2) + ->to(1) + ->extra(['hello' => 'world']) + ->sendOnce(); + $this->assertTrue($sent); + + $notifications = ModelNotification::all(); + $this->assertCount(2, $notifications); + $this->assertInstanceOf(EloquentCollection::class, $notifications); + } +} diff --git a/tests/integration/Managers/SenderManagerTest.php b/tests/integration/Managers/SenderManagerTest.php new file mode 100644 index 0000000..9d50554 --- /dev/null +++ b/tests/integration/Managers/SenderManagerTest.php @@ -0,0 +1,30 @@ +setExpectedException(BadMethodCallException::class); + + $manager = app('notifynder.sender'); + $manager->sendSingle(); + } + + public function testCallUndefinedMethod() + { + $this->setExpectedException(BadMethodCallException::class); + + $manager = app('notifynder.sender'); + $manager->undefinedMethod([]); + } + + public function testCallFailingSender() + { + $this->setExpectedException(BadFunctionCallException::class); + + $manager = app('notifynder.sender'); + $manager->extend('sendFail', function () { + }); + $manager->sendFail([]); + } +} diff --git a/tests/integration/Notifable/NotifableTest.php b/tests/integration/Notifable/NotifableTest.php deleted file mode 100644 index a87bea6..0000000 --- a/tests/integration/Notifable/NotifableTest.php +++ /dev/null @@ -1,170 +0,0 @@ - 1, - 'type' => 'Fenos\Tests\Models\User' - ]; - - /** - * @var Notification - */ - protected $notification; - - /** - * @var User - */ - protected $user; - - /** - * Set Up Test - */ - public function setUp() - { - parent::setUp(); - $this->notification = app('notifynder.notification'); - $this->user = Factory::create(User::class); - } - - /** - * @test - */ - public function it_count_notification_not_read() { - - $this->createMultipleNotifications(['read' => 1]); - - $count = $this->user->countNotificationsNotRead(); - - $this->assertEquals(0,$count); - } - - /** - * It read all notifications - * - * @method readLimitNotifications - * @test - */ - function it_real_all_notifications() - { - $this->createMultipleNotifications(); - - $read = $this->user->readAllNotifications(); - - $this->assertEquals(10,$read); - } - - /** - * It read limiting amount the of - * notifications - * - * @method readLimitNotifications - * @test - */ - function it_read_a_limit_of_notifications() - { - $this->createMultipleNotifications(); - - $read = $this->user->readLimitNotifications(6); - - $this->assertEquals(6,$read); - } - - /** - * It delete limiting the amount of - * notifications - * - * @method deleteLimitNotifications - * @test - */ - function it_delete_limit_notifications() - { - $this->createMultipleNotifications(); - - $deleted = $this->user->deleteLimitNotifications(4); - - $this->assertEquals(4,$deleted); - } - - /** - * It delete all notifications - * - * @method deleteAllNotifications - * @test - */ - function it_delete_all_notifications() - { - $this->createMultipleNotifications(); - - $deleted = $this->user->deleteAllNotifications(); - - $this->assertEquals($this->multiNotificationsNumber,$deleted); - } - - /** - * Get notifications unread - * - * @method - * @test - */ - function it_get_notifications_not_read() - { - // 20 total - $this->createMultipleNotifications(); - $this->createMultipleNotifications(); - $this->user->readLimitNotifications(10); // 10 read - - $getNotificationNotRead = $this->user->getNotificationsNotRead(); - - $this->assertCount(10,$getNotificationNotRead); - } - - /** - * Get all notifications - * - * @method getNotifications - * @test - */ - function it_get_all_notification_of_the_current_user() - { - $this->createMultipleNotifications(); - - $notifications = $this->user->getNotifications(); - - $this->assertCount(10,$notifications); - } - - /** - * get the last notification - * - * @method getLastNotification - * @test - */ - function it_get_last_notification() - { - $this->createMultipleNotifications(); - - $lastNotification = $this->user->getLastNotification(); - - $notification = Notification::orderBy('created_at','desc')->first(); - - $this->assertEquals($notification->id,$lastNotification->id); - } -} \ No newline at end of file diff --git a/tests/integration/Notifications/NotificationTest.php b/tests/integration/Notifications/NotificationTest.php deleted file mode 100755 index 138ce49..0000000 --- a/tests/integration/Notifications/NotificationTest.php +++ /dev/null @@ -1,83 +0,0 @@ - 1, - 'type' => 'Fenos\Tests\Models\User' - ]; - - /** - * Set Up Test - */ - public function setUp() - { - parent::setUp(); - $this->notification = app('notifynder.notification'); - } - - /** @test */ - function it_retrieve_notification_with_parsed_body() - { - $extraValues = json_encode(['look' => 'Amazing']); - $category = $this->createCategory(['text' => 'parse this {extra.look} value']); - - $notification = $this->createNotification(['extra' => $extraValues,'category_id' => $category->id]); - - $notifications = $this->notification->getNotRead($notification->to->id); - - $bodyParsed = 'parse this Amazing value'; - $this->assertEquals($bodyParsed,$notifications[0]->text); - } - - /** @test */ - function it_retrieve_notification_by_limiting_the_number() - { - $this->createMultipleNotifications(); - - // set polymorphic to true - app('config')->set('notifynder.polymorphic',true); - - $notification = $this->createNotification(['extra' => 'Amazing']); - - $notifications = $this->notification->entity($this->to['type']) - ->getAll($notification->to->id); - - $this->assertCount(1,$notifications); - } - - /** @test */ - function it_retrieve_notification_by_paginating_the_number() - { - app('config')->set('notifynder.polymorphic',false); - $extraValues = json_encode(['look' => 'Amazing']); - - $category = $this->createCategory(['text' => 'parse this {extra.look} value']); - - $notification = $this->createNotification(['extra' => $extraValues,'category_id' => $category->id]); - - $notifications = $this->notification->getNotRead($notification->to->id,10,true); - - $bodyParsed = 'parse this Amazing value'; - $this->assertEquals($bodyParsed,$notifications->items()[0]->text); - } -} \ No newline at end of file diff --git a/tests/integration/Notifications/NotifynderTest.php b/tests/integration/Notifications/NotifynderTest.php deleted file mode 100755 index 2d7c433..0000000 --- a/tests/integration/Notifications/NotifynderTest.php +++ /dev/null @@ -1,138 +0,0 @@ -notifynder = app('notifynder'); - } - - /** @test */ - function it_call_an_extended_method() - { - $this->createCategory(['name' => 'customs']); - - $this->notifynder->extend('sendCustom', function($notification,$app) { - return new CustomDefaultSender($notification,$app->make('notifynder')); - }); - - $notifications = $this->notifynder - ->category('customs') - ->url('w') - ->from(1) - ->to(1) - ->sendCustom(); - - $this->assertEquals('w',$notifications->url); - } - - /** @test */ - function it_send_a_notification_with_the_new_way() - { - $this->createCategory(['name' => 'custom']); - - $notifications = $this->notifynder - ->category('custom') - ->url('w') - ->from(1) - ->to(1); - - $notifications = $this->notifynder->send($notifications); - $this->assertEquals('w',$notifications->url); - } - - - /** @test */ - function it_send_using_notifynder_as_an_array() - { - $this->createCategory(['name' => 'custom']); - - $this->notifynder['category'] = 'custom'; - $this->notifynder['url'] = 'w'; - $this->notifynder['from'] = 1; - $this->notifynder['to'] = 1; - $notification = $this->notifynder->send(); - - $this->assertEquals('w',$notification->url); - } - - /** @test */ - function it_send_using_notifynder_as_an_object() - { - $this->createCategory(['name' => 'custom']); - - $notifynder = $this->notifynder; - $notifynder->category = 'custom'; - $notifynder->url = 'w'; - $notifynder->from = 1; - $notifynder->to = 1; - $notification = $notifynder->send(); - - $this->assertEquals('w',$notification->url); - } - - /** @test */ - function it_store_extra_field_as_json() - { - $this->createCategory(['name' => 'custom']); - - $extra = ['notifynder' => 'amazing']; - - $notifications = $this->notifynder - ->category('custom') - ->extra($extra) - ->url('w') - ->from(1) - ->to(1); - - $notifications = $this->notifynder->send($notifications); - $this->assertEquals(json_encode($extra),$notifications->extra); - } - - /** - * It send multiple Notifications - * - * @method send - * @group failing - * @test - */ - function it_send_multiple_notifications() - { - Factory::times(10)->create(User::class); - $this->createCategory(['name' => 'me']); - - $allUsers = User::all(); - - $this->notifynder->loop($allUsers, function($builder,$user) { - - $builder->category('me') - ->url('you') - ->from(1) - ->to($user->id); - - })->send(); - - // should send 10 notifications - $notifications = Notification::all(); - - $this->assertCount(10,$notifications); - } -} \ No newline at end of file diff --git a/tests/integration/Repositories/GroupCategoryReposutoryTest.php b/tests/integration/Repositories/GroupCategoryReposutoryTest.php deleted file mode 100755 index 207672a..0000000 --- a/tests/integration/Repositories/GroupCategoryReposutoryTest.php +++ /dev/null @@ -1,68 +0,0 @@ -categoryGroup = app('notifynder.group.category'); - } - - /** @test */ - function it_add_a_category_to_a_group_id() - { - $category = $this->createCategory(); - $group = $this->createGroup(); - - $this->categoryGroup->addCategoryToGroupById( - $group->id, - $category->id - ); - - $this->assertEquals($group->categories[0]->name,$category->name); - } - - /** @test */ - function it_add_a_category_to_a_group_by_name() - { - $category = $this->createCategory(); - $group = $this->createGroup(); - - $this->categoryGroup->addCategoryToGroupByName( - $group->name, - $category->name - ); - - $this->assertEquals($group->categories[0]->name,$category->name); - } - - /** @test */ - function it_add_multiple_categories_to_a_group_by_name() - { - $category1 = $this->createCategory(); - $category2 = $this->createCategory(); - $group = $this->createGroup(); - - $this->categoryGroup->addMultipleCategoriesToGroup( - $group->name, - [$category1->name, $category2->name] - ); - - $this->assertCount(2,$group->categories); - } -} \ No newline at end of file diff --git a/tests/integration/Repositories/GroupRepositoryTest.php b/tests/integration/Repositories/GroupRepositoryTest.php deleted file mode 100755 index 278a8e6..0000000 --- a/tests/integration/Repositories/GroupRepositoryTest.php +++ /dev/null @@ -1,66 +0,0 @@ -group = app('notifynder.group.repository'); - } - - /** @test */ - function it_find_a_group_by_id() - { - $group = $this->createGroup(); - - $findGroup = $this->group->find($group->id); - - $this->assertEquals($group->id,$findGroup->id); - } - - /** @test */ - function it_find_a_group_by_name() - { - $group_name = 'mygroup'; - $this->createGroup(['name' => $group_name]); - - $group = $this->group->findByName($group_name); - - $this->assertEquals($group_name,$group->name); - } - - /** @test */ - function it_create_a_group() - { - $groupData = 'mygroup'; - - $group = $this->group->create($groupData); - - $this->assertEquals($groupData,$group->name); - } - - /** @test */ - function it_delete_a_group_by_id() - { - $group = $this->createGroup(); - - $this->group->delete($group->id); - - $this->assertCount(0, NotificationGroup::all()); - } -} \ No newline at end of file diff --git a/tests/integration/Repositories/NotificationCategoryDBTest.php b/tests/integration/Repositories/NotificationCategoryDBTest.php deleted file mode 100755 index 203ebf6..0000000 --- a/tests/integration/Repositories/NotificationCategoryDBTest.php +++ /dev/null @@ -1,97 +0,0 @@ -categoryRepo = app('notifynder.category.repository'); - } - - /** @test */ - function it_find_a_category_by_id() - { - $record = $this->createCategory(); - - $category = $this->categoryRepo->find($record->id); - - $this->assertEquals(1,$category->id); - } - - /** @test */ - function it_find_a_category_by_name() - { - $categoryName = "test.category"; - - $this->createCategory(['name' => $categoryName]); - - $category = $this->categoryRepo->findByName($categoryName); - - $this->assertEquals($categoryName,$category->name); - } - - /** @test */ - function it_find_categories_giving_multiple_names() - { - $categoryNames = ['test.first','test.second']; - - $this->createCategory(['name' => $categoryNames[0]]); - $this->createCategory(['name' => $categoryNames[1]]); - - $categories = $this->categoryRepo->findByNames($categoryNames); - - $this->assertCount(2,$categories); - } - - /** @test */ - function it_add_a_new_category() - { - $categoryData = Factory::build('Fenos\Notifynder\Models\NotificationCategory'); - - $createCategory = $this->categoryRepo->add($categoryData->name,$categoryData->text); - - $this->assertEquals($categoryData->name,$createCategory->name); - } - - /** @test */ - function it_delete_a_category_by_id() - { - $categoryToDelete = $this->createCategory(); - - $this->categoryRepo->delete($categoryToDelete->id); - - $tryToFindThatCategory = $this->categoryRepo->find($categoryToDelete->id); - - $this->assertEquals($tryToFindThatCategory,null); - } - - /** @test */ - function it_delete_a_category_by_name() - { - $categoryToDelete = $this->createCategory(); - - $this->categoryRepo->deleteByName($categoryToDelete->name); - - $tryToFindThatCategory = $this->categoryRepo->findByName($categoryToDelete->name); - - $this->assertEquals($tryToFindThatCategory,null); - } -} \ No newline at end of file diff --git a/tests/integration/Repositories/NotificationRepositoryDBTest.php b/tests/integration/Repositories/NotificationRepositoryDBTest.php deleted file mode 100755 index 9f17ba6..0000000 --- a/tests/integration/Repositories/NotificationRepositoryDBTest.php +++ /dev/null @@ -1,279 +0,0 @@ - 1, - 'type' => 'User' - ]; - - /** - * @var int - */ - protected $multiNotificationsNumber = 10; - - /** - * @var int - */ - protected $to_id = 1; - - /** - * SetUp Tests - */ - public function setUp() - { - parent::setUp(); - - $this->notificationRepo = app('notifynder.notification.repository'); - } - - /** @test */ - function it_find_a_notification_by_id() - { - $notificationToSearch = $this->createNotification(); - - $notification = $this->notificationRepo->find($notificationToSearch->id); - - $this->assertEquals($notificationToSearch->id,$notification->id); - } - - /** @test */ - function it_send_a_single_notification() - { - $notificationToSend = $this->buildNotification(); - - $notification = $this->notificationRepo->storeSingle($notificationToSend); - - $this->assertEquals($notificationToSend['to_id'],$notification->to_id); - $this->assertEquals($notificationToSend['to_type'],$notification->to_type); - } - - /** @test */ - function it_send_multiple_notification() - { - $notificationsToSend[0] = $this->buildNotification(); - $notificationsToSend[1] = $this->buildNotification(); - - $storeMultipleNotificaations = $this->notificationRepo->storeMultiple($notificationsToSend); - - $notifications = Notification::all(); - - $this->assertCount(2,$notifications); - $this->assertEquals(2,$storeMultipleNotificaations); - } - - /** @test */ - function it_read_one_notification_by_id() - { - $notificationToRead = $this->createNotification(); - - $notificationRead = $this->notificationRepo->readOne($notificationToRead); - - $this->assertEquals(1,$notificationRead->read); - } - - /** @test */ - function it_read_limit_the_number_of_notifications_of_the_given_entity() - { - $this->createMultipleNotifications(); - - $readFive = $this->notificationRepo->readLimit( - $this->to['id'],$this->to['type'],5,'asc' - ); - - $notificationsRead = Notification::whereRead(1)->get(); - - $this->assertEquals(5,$readFive); - $this->assertCount(5,$notificationsRead); - } - - /** @test */ - function it_read_all_the_notifications_of_the_given_entity() - { - $this->createMultipleNotifications(); - - $notificationRead = $this->notificationRepo->readAll( - $this->to['id'],$this->to['type'] - ); - - $this->assertEquals(10,$notificationRead); - } - - /** @test */ - function it_delete_a_notification_by_id() - { - $notificationToDelete = $this->createNotification(); - - $deleted = $this->notificationRepo->delete($notificationToDelete->id); - - $this->assertEquals(1,$deleted); - $this->assertCount(0,Notification::all()); - } - - /** @test */ - function it_delete_all_the_notification_of_the_given_entity() - { - $this->createMultipleNotifications(); - - $deleted = $this->notificationRepo->deleteAll( - $this->to['id'],$this->to['type'] - ); - - $this->assertEquals(10,$deleted); - $this->assertCount(0,Notification::all()); - } - - /** @test */ - function it_delete_notifications_limit_the_number_of_the_given_entity() - { - $this->createMultipleNotifications(); - - $notificationsDeleted = $this->notificationRepo->deleteLimit( - $this->to['id'],$this->to['type'],5,'asc' - ); - - $this->assertEquals(5,$notificationsDeleted); - $this->assertCount(5,Notification::all()); - } - - /** @test */ - function it_count_notification_not_read() - { - $this->createMultipleNotifications(); - - $countNotRead = $this->notificationRepo->countNotRead( - $this->to['id'],$this->to['type'] - ); - - $this->assertEquals($this->multiNotificationsNumber,$countNotRead); - } - - /** @test */ - function it_delete_all_notification_by_category() - { - $category = $this->createCategory(['name' => 'test']); - - $this->createNotification(['category_id' => $category->id]); - $this->createNotification(['category_id' => $category->id]); - $this->createNotification(); - - $this->notificationRepo->deleteByCategory($category->name); - - $this->assertCount(1, Notification::all()); - } - - /** @test */ - function it_delete_all_notification_expired_by_category_name() - { - $category = $this->createCategory(['name' => 'test']); - - $this->createNotification([ - 'category_id' => $category->id, - 'expire_time' => Carbon\Carbon::now()->subDays(1) - ]); - - $this->createNotification([ - 'category_id' => $category->id, - 'expire_time' => Carbon\Carbon::now()->subDays(1) - ]); - - $this->createNotification([ - 'category_id' => $category->id, - 'expire_time' => Carbon\Carbon::now()->subDays(1) - ]); - - $this->createNotification([ - 'category_id' => $category->id, - 'expire_time' => Carbon\Carbon::now()->addDays(1) - ]); - - $this->notificationRepo->deleteByCategory($category->name,true); - - $this->assertCount(1, Notification::all()); - } - - /** @test */ - function it_get_the_last_notificiation_sent() - { - $category = $this->createCategory(['name' => 'test']); - - $this->createNotification([ - 'category_id' => $category->id, - 'url' => 'first', - 'to_id' => 1, - 'created_at' => Carbon\Carbon::now()->addDay(1) - ]); - - $this->createNotification([ - 'category_id' => $category->id, - 'url' => 'second', - 'to_id' => 1, - 'created_at' => Carbon\Carbon::now()->addDay(2) - ]); - - $notification = $this->notificationRepo->getLastNotification(1,null); - - $this->assertEquals('second',$notification->url); - } - - /** @test */ - function it_get_the_last_notificiation_sent_by_category() - { - $category1 = $this->createCategory(['name' => 'test']); - $category2 = $this->createCategory(['name' => 'test2']); - - $this->createNotification([ - 'category_id' => $category1->id, - 'url' => 'first', - 'to_id' => 1, - 'created_at' => Carbon\Carbon::now()->addDay(1) - ]); - - $this->createNotification([ - 'category_id' => $category1->id, - 'url' => 'second', - 'to_id' => 1, - 'created_at' => Carbon\Carbon::now()->addDay(2) - ]); - - $this->createNotification([ - 'category_id' => $category2->id, - 'url' => 'third', - 'to_id' => 1, - 'created_at' => Carbon\Carbon::now()->addDay(3) - ]); - - $notificationByName = $this->notificationRepo->getLastNotificationByCategory('test',1,null); - $notificationById = $this->notificationRepo->getLastNotificationByCategory($category1->id,1,null); - - $this->assertEquals('second',$notificationByName->url); - $this->assertEquals('second',$notificationById->url); - } - - /** - * Shortcut to build a new notification - * - * @param array $data - * @return array - */ - protected function buildNotification(array $data = []) - { - return Factory::build(Notification::class,$data)->toArray(); - } - - -} \ No newline at end of file diff --git a/tests/integration/Senders/OnceSenderTest.php b/tests/integration/Senders/OnceSenderTest.php new file mode 100644 index 0000000..ff50928 --- /dev/null +++ b/tests/integration/Senders/OnceSenderTest.php @@ -0,0 +1,16 @@ +set('notification_model', \Fenos\Tests\Models\FakeModel::class); + + $this->setExpectedException(BadMethodCallException::class); + + $manager = app('notifynder.sender'); + $manager->sendOnce([ + new \Fenos\Notifynder\Builder\Notification(), + ]); + } +} diff --git a/tests/integration/Senders/SendersTest.php b/tests/integration/Senders/SendersTest.php deleted file mode 100755 index ad6070a..0000000 --- a/tests/integration/Senders/SendersTest.php +++ /dev/null @@ -1,135 +0,0 @@ -set( - 'notifynder.notification_model', - 'Fenos\Notifynder\Models\Notification' - ); - - $this->senders = app('notifynder.sender'); - $this->builder = app('notifynder.builder'); - $this->group = app('notifynder.group'); - } - - /** @test */ - function it_send_now_a_single_notification() - { - $category_name = 'my.category'; - $this->createCategory(['name' => $category_name]); - - $singleNotification = $this->builder->category($category_name) - ->to(1) - ->from(2) - ->url('www.notifynder.io') - ->toArray(); - - // Send Single - $this->senders->sendNow($singleNotification); - - $this->assertCount(1, Notification::all()); - } - - /** @test */ - function it_send_now_a_mutiple_notification() - { - $category_name = 'my.category'; - $this->createCategory(['name' => $category_name]); - - $user_ids = [1,2]; - - $sendMultiple = $this->builder->loop($user_ids, - function(NotifynderBuilder $builder, $value) use ($category_name) { - - return $builder->category($category_name) - ->to($value) - ->from(2) - ->url('www.notifynder.io') - ->toArray(); - }); - - // Send Single - $this->senders->sendNow($sendMultiple); - - $this->assertCount(2, Notification::all()); - } - - /** @test */ - function it_send_a_group_of_notification() - { - $group = $this->createGroup(['name' => 'mygroud']); - $category1 = $this->createCategory(); - $category2 = $this->createCategory(); - $category3 = $this->createCategory(); - - $this->group->addMultipleCategoriesToGroup($group->name, - $category1->name, - $category2->name, - $category3->name - ); - - $this->senders->sendGroup($group->name,[ - 'from_id' => 1, - 'to_id' => 2, - 'url' => 'www.notifynder.io' - ]); - - $this->assertCount(3,Notification::all()); - } - - /** @test */ - function it_send_with_an_custom_sender() - { - $this->senders->extend('sendCustom', function($notification,$app) { - return new CustomDefaultSender($notification,$app->make('notifynder')); - }); - - $category_name = 'my.category'; - $this->createCategory(['name' => $category_name]); - - $singleNotification = $this->builder->category($category_name) - ->to(1) - ->from(2) - ->url('www.notifynder.io') - ->toArray(); - - $this->senders->sendCustom($singleNotification); - - $this->assertCount(1, Notification::all()); - } -} \ No newline at end of file diff --git a/tests/integration/Traits/NotifableTest.php b/tests/integration/Traits/NotifableTest.php new file mode 100644 index 0000000..fd8c728 --- /dev/null +++ b/tests/integration/Traits/NotifableTest.php @@ -0,0 +1,108 @@ +createUser(); + $notifynder = $user->notifynder(1); + $this->assertInstanceOf(NotifynderManager::class, $notifynder); + $notifynder->from(1)->to(2); + $builder = $notifynder->builder(); + $this->assertInstanceOf(Builder::class, $builder); + $notification = $builder->getNotification(); + $this->assertInstanceOf(Notification::class, $notification); + $this->assertSame(1, $notification->category_id); + } + + public function testSendNotificationFrom() + { + $user = $this->createUser(); + $notifynder = $user->sendNotificationFrom(1); + $this->assertInstanceOf(NotifynderManager::class, $notifynder); + $notifynder->to(2); + $builder = $notifynder->builder(); + $this->assertInstanceOf(Builder::class, $builder); + $notification = $builder->getNotification(); + $this->assertInstanceOf(Notification::class, $notification); + $this->assertSame(1, $notification->category_id); + $this->assertSame(1, $notification->from_id); + } + + public function testSendNotificationTo() + { + $user = $this->createUser(); + $notifynder = $user->sendNotificationTo(1); + $this->assertInstanceOf(NotifynderManager::class, $notifynder); + $notifynder->from(2); + $builder = $notifynder->builder(); + $this->assertInstanceOf(Builder::class, $builder); + $notification = $builder->getNotification(); + $this->assertInstanceOf(Notification::class, $notification); + $this->assertSame(1, $notification->category_id); + $this->assertSame(1, $notification->to_id); + $notifynder->send(); + $this->assertCount(1, $user->getNotificationRelation); + } + + public function testNotificationsHasMany() + { + $user = $this->createUser(); + $user + ->sendNotificationTo(1) + ->from(2) + ->send(); + $this->assertCount(1, $user->getNotificationRelation); + } + + public function testNotificationsMorphMany() + { + notifynder_config()->set('polymorphic', true); + + $user = $this->createUser(); + $this->sendNotificationTo($user); + $car = $this->createCar(); + $this->sendNotificationTo($car); + $this->assertCount(1, $user->getNotificationRelation); + $this->assertCount(1, $car->getNotificationRelation); + } + + public function testGetNotificationsDefault() + { + $user = $this->createUser(); + $this->sendNotificationsTo($user, 25); + $this->assertCount(25, $user->getNotifications()); + } + + public function testGetNotificationsLimited() + { + $user = $this->createUser(); + $this->sendNotificationsTo($user, 25); + $this->assertCount(10, $user->getNotifications(10)); + } + + public function testReadStatusRelatedMethods() + { + $user = $this->createUser(); + $this->sendNotificationsTo($user, 25); + $this->assertSame(25, $user->countUnreadNotifications()); + $this->assertSame(25, $user->readAllNotifications()); + $this->assertSame(0, $user->countUnreadNotifications()); + $this->assertSame(25, $user->unreadAllNotifications()); + $this->assertSame(25, $user->countUnreadNotifications()); + $notification = $user->getNotificationRelation->first(); + $this->assertTrue($user->readNotification($notification)); + $this->assertSame(24, $user->countUnreadNotifications()); + $this->assertTrue($user->unreadNotification($notification->getKey())); + $this->assertSame(25, $user->countUnreadNotifications()); + + + $user2 = $this->createUser(); + $this->sendNotificationsTo($user2, 5); + $this->assertFalse($user->readNotification($user2->getNotificationRelation->first())); + } +} diff --git a/tests/integration/Translator/TranslatorTest.php b/tests/integration/Translator/TranslatorTest.php deleted file mode 100755 index 07f0f57..0000000 --- a/tests/integration/Translator/TranslatorTest.php +++ /dev/null @@ -1,37 +0,0 @@ -set('notifynder.translations',$translations); - $this->translator = app('notifynder.translator'); - } - - /** @test */ - function it_translate_a_notification() - { - $translation = $this->translator->translate('it','welcome'); - - $this->assertEquals('benvenuto',$translation); - } -} \ No newline at end of file diff --git a/tests/integration/Translator/translations.php b/tests/integration/Translator/translations.php deleted file mode 100755 index 74be29f..0000000 --- a/tests/integration/Translator/translations.php +++ /dev/null @@ -1,9 +0,0 @@ - [ - 'welcome' => 'benvenuto' - ] - -]; \ No newline at end of file diff --git a/tests/migrations/2014_08_01_164248_create_users_table.php b/tests/migrations/2014_08_01_164248_create_users_table.php old mode 100755 new mode 100644 index 2973ba7..204f506 --- a/tests/migrations/2014_08_01_164248_create_users_table.php +++ b/tests/migrations/2014_08_01_164248_create_users_table.php @@ -3,31 +3,30 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; -class CreateUsersTable extends Migration { - - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::create('users', function(Blueprint $table) { +class CreateUsersTable extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::create('users', function (Blueprint $table) { $table->increments('id'); - $table->string('name'); - $table->string('surname'); + $table->string('firstname'); + $table->string('lastname'); $table->timestamps(); }); - } + } - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { Schema::drop('users'); - } - + } } diff --git a/tests/migrations/2016_08_26_100534_create_cars_table.php b/tests/migrations/2016_08_26_100534_create_cars_table.php new file mode 100644 index 0000000..8a534cc --- /dev/null +++ b/tests/migrations/2016_08_26_100534_create_cars_table.php @@ -0,0 +1,32 @@ +increments('id'); + $table->string('brand'); + $table->string('model'); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::drop('cars'); + } +} diff --git a/tests/models/Car.php b/tests/models/Car.php new file mode 100644 index 0000000..694e8fd --- /dev/null +++ b/tests/models/Car.php @@ -0,0 +1,19 @@ +