From 8eaf12a4e35d035d77e35d607fca1c451812ba4b Mon Sep 17 00:00:00 2001 From: Adam Kadlec Date: Wed, 5 Apr 2017 18:13:00 +0200 Subject: [PATCH] - Fixing wrong up --- bower.json | 11 +- composer.json | 18 +- docs/en/index.md | 100 ++-- public/js/ipub.formPhone.js | 522 ------------------ public/readme.md | 27 +- readme.md | 30 +- src/IPub/FormPhone/Controls/Phone.php | 522 ------------------ src/IPub/FormPhone/DI/FormPhoneExtension.php | 51 -- src/IPub/FormPhone/Exceptions/IException.php | 21 - .../Exceptions/InvalidArgumentException.php | 21 - .../Exceptions/NoValidCountryException.php | 21 - .../Exceptions/NoValidTypeException.php | 21 - src/IPub/FormPhone/Forms/PhoneValidator.php | 126 ----- src/IPub/FormPhone/Locale/Locale.php | 55 -- tests/IPubTests/FormPhone/PhoneInputTest.phpt | 395 ------------- .../FormPhone/PhoneValidationTest.phpt | 308 ----------- tests/IPubTests/FormPhone/files/config.neon | 3 - tests/php.ini-unix | 2 - tests/php.ini-win | 2 - 19 files changed, 88 insertions(+), 2168 deletions(-) delete mode 100644 public/js/ipub.formPhone.js delete mode 100644 src/IPub/FormPhone/Controls/Phone.php delete mode 100644 src/IPub/FormPhone/DI/FormPhoneExtension.php delete mode 100644 src/IPub/FormPhone/Exceptions/IException.php delete mode 100644 src/IPub/FormPhone/Exceptions/InvalidArgumentException.php delete mode 100644 src/IPub/FormPhone/Exceptions/NoValidCountryException.php delete mode 100644 src/IPub/FormPhone/Exceptions/NoValidTypeException.php delete mode 100644 src/IPub/FormPhone/Forms/PhoneValidator.php delete mode 100644 src/IPub/FormPhone/Locale/Locale.php delete mode 100644 tests/IPubTests/FormPhone/PhoneInputTest.phpt delete mode 100644 tests/IPubTests/FormPhone/PhoneValidationTest.phpt delete mode 100644 tests/IPubTests/FormPhone/files/config.neon diff --git a/bower.json b/bower.json index 832bd98..b3a3e1e 100644 --- a/bower.json +++ b/bower.json @@ -1,13 +1,12 @@ { - "name": "ipub-form-phone", - "description": "Forms control for adding phone filed for Nette Framework", - "keywords": ["nette", "form", "phone", "ipub", "ipublikuj", "framework", "tools"], + "name": "ipub-form-slug", + "description": "Forms control for adding slug filed for Nette Framework", + "keywords": ["nette", "form", "slug", "ipub", "ipublikuj", "framework", "tools"], "main": [ - "public/js/ipub.formPhone.js" + "public/js/ipub.formSlug.js" ], "dependencies": { - "jquery": "~2.1.0", - "ipub-phone": "^1.2.0" + "jquery": "~2.1.0" }, "authors": [ { diff --git a/composer.json b/composer.json index 1a5d25d..04ccd6e 100644 --- a/composer.json +++ b/composer.json @@ -1,9 +1,9 @@ { - "name" : "ipub/form-phone", + "name" : "ipub/form-slug", "type" : "library", - "description" : "Forms control for adding phone filed for Nette Framework", - "keywords" : ["nette", "form", "phone", "ipub", "ipublikuj", "framework", "tools"], - "homepage" : "https://github.com/iPublikuj/form-phone", + "description" : "Forms control for adding slug filed for Nette Framework", + "keywords" : ["nette", "form", "sluggable", "ipub", "ipublikuj", "framework", "tools"], + "homepage" : "https://github.com/iPublikuj/form-slug", "license" : ["GPL-2.0", "GPL-3.0"], "authors": [ @@ -14,15 +14,13 @@ } ], - "support": { + "support":{ "email" :"support@ipublikuj.eu", - "issues" :"https://github.com/iPublikuj/form-phone/issues" + "issues" :"https://github.com/iPublikuj/form-slug/issues" }, "require": { - "php" : ">=7.0.0", - - "ipub/phone" : "~1.2", + "php" : ">=7.0", "nette/application" : "~2.3@dev", "nette/di" : "~2.3@dev", @@ -46,7 +44,7 @@ "autoload": { "psr-0": { - "IPub\\FormPhone\\": "src/" + "IPub\\FormSlug\\": "src/" } } } diff --git a/docs/en/index.md b/docs/en/index.md index 2cb9d22..f37f364 100644 --- a/docs/en/index.md +++ b/docs/en/index.md @@ -1,26 +1,26 @@ # Quickstart -This extension extend your [Nette](http://nette.org) forms with phone control field with specific phone number validation, based on [iPublikuj:Phone!](https://github.com/iPublikuj/phone) +This extension extend your [Nette](http://nette.org) forms with slug control field with automatic slug creation based on selected fields. ## Installation -The best way to install ipub/form-phone is using [Composer](http://getcomposer.org/): +The best way to install ipub/form-slug is using [Composer](http://getcomposer.org/): ```sh -$ composer require ipub/form-phone +$ composer require ipub/form-slug:@dev ``` After that you have to register extension in config.neon. ```neon extensions: - formPhone: IPub\FormPhone\DI\FormPhoneExtension + formSlug: IPub\FormSlug\DI\FormSlugExtension ``` And you also need to include static files into your page: ```html - + ``` @@ -29,86 +29,70 @@ note: You have to upload static files from **client-site** folder to your projec ## Usage ```php -$form->addPhone('phone', 'Phone number:'); +$form->addSlug('slug', 'Slug:'); ``` -This control return values as normal text input, so you can access your phone like this: +You can connect other text inputs to this field and activate auto-generation slug, for example from item name: ```php -$phone = $form->values->phone; -``` - -Returned value is instance of IPub\Phone\Entities\Phone or null if the given phone number is not valid. - -This control will render two elements, one select box where you can choose country prefix and one text box where you put your national part of number. +$form->addText('name', 'Name:') -### Validation +$form->addSlug('slug', 'Slug:') + ->addField($form['name']); +``` -Field can be validated as usual text fields in nette, but phone number can be validated with custom validator: +You can add more than one field: ```php -$form->addPhone('phone', 'Phone number:') - ->addCondition(\Nette\Application\UI\Form::FILLED) - ->addRule(\IPub\FormPhone\Forms\PhoneValidator::PHONE, 'Phone is invalid'); +$form->addSlug('slug', 'Slug:') + ->addField($form['name']) + ->addField($form['subname']); ``` -#### Limit to country - -By default is country detection set to AUTO, if you want to specify allowed country/ies you can set them: +This control return values as normal text input, so you can acces your slug like this: ```php -$form->addPhone('phone', 'Phone number:') - ->addAllowedCountry('CZ') - ->addAllowedCountry('GB') - ->addCondition(\Nette\Application\UI\Form::FILLED) - ->addRule(\IPub\FormPhone\Forms\PhoneValidator::PHONE, 'Phone is invalid'); +$slug = $form->values->slug; ``` -or +### Validation -```php -$form->addPhone('phone', 'Phone number:') - ->setAllowedCountries(['CZ', 'GB']) - ->addCondition(\Nette\Application\UI\Form::FILLED) - ->addRule(\IPub\FormPhone\Forms\PhoneValidator::PHONE, 'Phone is invalid'); -``` +Validation can be done as on usual text input, no changes are made here. -Now only phone numbers from Czech Republic or Great Britain are allowed. +### Custom templates and rendering -#### Limit to phone type +This control come with templating feature, that mean form element of this control is rendered in latte template. There are 3 predefined templates: -You can limit allowed phone to specific phone types eg. mobile, land line etc. +* bootstrap.latte if you are using [Twitter Bootstrap](http://getbootstrap.com/) +* uikit.latte if you are using [YooTheme UIKit](http://getuikit.com/) +* default.latte for custom styling (this template is loaded as default) -```php -$form->addPhone('phone', 'Phone number:') - ->addAllowedPhoneType(\IPub\Phone\Phone::TYPE_MOBILE) - ->addCondition(\Nette\Application\UI\Form::FILLED) - ->addRule(\IPub\FormPhone\Forms\PhoneValidator::PHONE, 'Phone is invalid'); -``` +You can also define you own template if you need to fit this control into your layout. -or +Template can be set in form definition: ```php -$form->addPhone('phone', 'Phone number:') - ->setAllowedPhoneTypes([\IPub\Phone\Phone::TYPE_MOBILE, \IPub\Phone\Phone::TYPE_PAGER]) - ->addCondition(\Nette\Application\UI\Form::FILLED) - ->addRule(\IPub\FormPhone\Forms\PhoneValidator::PHONE, 'Phone is invalid'); +$form->addSlug('slug', 'Slug:') + ->setTemplateFile('path/to/your/template.latte'); ``` -List of allowed phone types is available in [iPublikuj:Phone!](https://github.com/iPublikuj/phone/blob/master/src/IPub/Phone/Phone.php#L39-L47) +or in manual renderer of the form: -### Manual rendering +```php +{?$form['slug']->setTemplateFile('path/to/your/template.latte')} +{input slug class => "some-custom-class"} +``` -Phone field can be rendered as usual, or manually with partial rendering: +and if you want to switch default template to **bootstrap** or **uikit** just it write into template setter: -```html -{form yourFormWithPhoneField} - // ... +```php +$form->addSlug('slug', 'Slug:') + ->setTemplateFile('bootstrap.latte'); +``` - {label phone /} - {input phone:country} - {input phone:number} +or - // ... -{/form} +```php +{?$form['slug']->setTemplateFile('bootstrap.latte')} +{input slug class => "some-custom-class"} ``` diff --git a/public/js/ipub.formPhone.js b/public/js/ipub.formPhone.js deleted file mode 100644 index ae7d43a..0000000 --- a/public/js/ipub.formPhone.js +++ /dev/null @@ -1,522 +0,0 @@ -/** - * ipub.formPhone.js - * - * @copyright More in license.md - * @license http://www.ipublikuj.eu - * @author Adam Kadlec - * @package iPublikuj:FormPhone! - * @subpackage java-script - * @since 1.0.0 - * - * @date 19.12.15 - */ - -/** - * Client-side script for iPublikuj:FormPhone! - * - * @author Adam Kadlec - * @package iPublikuj:FormPhone! - * @version 1.0.0 - * - * @param {jQuery} $ (version > 1.7) - * @param {Window} window - * @param {Document} document - * @param {Location} location - * @param {Navigator} navigator - */ -;(function ($, window, document, location, navigator) { - /* jshint laxbreak: true, expr: true */ - "use strict"; - - var IPub = window.IPub || {}; - - IPub.Forms = IPub.Forms || {}; - - /** - * Forms phone extension definition - * - * @param {jQuery} $element - * @param {Object} options - */ - IPub.Forms.Phone = function ($element, options) { - this.$element = $element; - - this.name = this.$element.prop('id'); - this.options = $.extend($.fn.ipubFormsPhone.defaults, options, this.$element.data('settings') || {}); - - this.isIphone = (window.orientation !== undefined); - this.isAndroid = navigator.userAgent.toLowerCase().indexOf("android") > -1; - this.isIE = window.navigator.appName == 'Microsoft Internet Explorer'; - }; - - IPub.Forms.Phone.prototype = - { - // Initial function. - init: function () { - if (this.isAndroid) return; // No support because caret positioning doesn't work on Android - - var that = this; - - this.mask = String(this.$element.find(":selected").data('mask')); - this.$phoneField = $(document.getElementsByName(this.options.field)[0]); - - this.$element.bind('change.ipub.forms.phone', function () { - that.mask = String(that.$element.find(":selected").data('mask')); - - that.attach(); - - // Perform initial check for existing values - that.checkVal(); - }); - - this.attach(); - this.listen(); - - // Perform initial check for existing values - this.checkVal(); - }, - - attach: function () { - var defs = this.options.definitions; - var len = this.mask.length; - - this.tests = new Array; - this.partialPosition = this.mask.length; - this.firstNonMaskPos = null; - - $.each(this.mask.split(''), $.proxy(function (i, c) { - if (c == '?') { - len--; - this.partialPosition = i; - - } else if (defs[c]) { - this.tests.push(new RegExp(defs[c])); - - if (this.firstNonMaskPos === null) { - this.firstNonMaskPos = this.tests.length - 1; - } - - } else { - this.tests.push(null); - } - - }, this)); - - this.buffer = $.map(this.mask.split(''), $.proxy(function (c, i) { - if (c != '?') return defs[c] ? this.options.placeholder : c; - }, this)); - - this.focusText = this.$phoneField.val(); - - this.$phoneField.data('rawMaskFn', $.proxy(function () { - return $.map(this.buffer, function (c, i) { - return this.tests[i] && c != this.options.placeholder ? c : null; - }).join(''); - }, this)) - }, - - listen: function () { - if (this.$phoneField.attr('readonly')) - return; - - var pasteEventName = (this.isIE ? 'paste' : 'input') + '.ipub.forms.phone'; - - this.$phoneField - .off('unmask.ipub.forms.phone') - .on('unmask.ipub.forms.phone', $.proxy(this.unmask, this)) - - .off('focus.ipub.forms.phone') - .on('focus.ipub.forms.phone', $.proxy(this.focusEvent, this)) - .off('blur.ipub.forms.phone') - .on('blur.ipub.forms.phone', $.proxy(this.blurEvent, this)) - - .off('keydown.ipub.forms.phone') - .on('keydown.ipub.forms.phone', $.proxy(this.keydownEvent, this)) - .off('keypress.ipub.forms.phone') - .on('keypress.ipub.forms.phone', $.proxy(this.keypressEvent, this)) - - .off(pasteEventName) - .on(pasteEventName, $.proxy(this.pasteEvent, this)); - }, - - checkVal: function (allow) { - var len = this.mask.length; - - // Try to place characters where they belong - var test = this.$phoneField.val(); - var lastMatch = -1; - - for (var i = 0, pos = 0; i < len; i++) { - if (this.tests[i]) { - this.buffer[i] = this.options.placeholder; - - while (pos++ < test.length) { - var c = test.charAt(pos - 1); - - if (this.tests[i].test(c)) { - this.buffer[i] = c; - lastMatch = i; - - break - } - } - - if (pos > test.length) { - break - } - - } else if (this.buffer[i] == test.charAt(pos) && i != this.partialPosition) { - pos++; - lastMatch = i; - } - } - - if (!allow && lastMatch + 1 < this.partialPosition) { - this.$phoneField.val(''); - this.clearBuffer(0, len); - - } else if (allow || lastMatch + 1 >= this.partialPosition) { - this.writeBuffer(); - - if (!allow) { - this.$phoneField.val(this.$phoneField.val().substring(0, lastMatch + 1)); - } - } - - return (this.partialPosition ? i : this.firstNonMaskPos) - }, - - // Helper Function for Caret positioning - caret: function (begin, end) { - if (this.$phoneField.length === 0) return; - - if (typeof begin == 'number') { - end = (typeof end == 'number') ? end : begin; - - return this.$phoneField.each(function () { - if (this.setSelectionRange) { - this.setSelectionRange(begin, end); - - } else if (this.createTextRange) { - var range = this.createTextRange(); - range.collapse(true); - range.moveEnd('character', end); - range.moveStart('character', begin); - range.select(); - } - }); - - } else { - if (this.$phoneField[0].setSelectionRange) { - begin = this.$phoneField[0].selectionStart; - end = this.$phoneField[0].selectionEnd; - - } else if (document.selection && document.selection.createRange) { - var range = document.selection.createRange(); - - begin = 0 - range.duplicate().moveStart('character', -100000); - end = begin + range.text.length; - } - - return { - begin: begin, - end: end - } - } - }, - - unmask: function () { - this.$phoneField - .unbind('.ipub.forms.phone') - .removeData('ipub.forms.phone'); - }, - - focusEvent: function () { - this.focusText = this.$phoneField.val(); - var len = this.mask.length; - var pos = this.checkVal(); - - this.writeBuffer() - - var that = this - - var moveCaret = function () { - if (pos == len) { - that.caret(0, pos); - - } else { - that.caret(pos) - } - } - - moveCaret() - setTimeout(moveCaret, 50) - }, - - blurEvent: function () { - this.checkVal(); - - if (this.$phoneField.val() !== this.focusText) { - this.$phoneField.trigger('change'); - this.$phoneField.trigger('input'); - } - }, - - keydownEvent: function (e) { - var k = e.which; - - // backspace, delete, and escape get special treatment - if (k == 8 || k == 46 || (this.isIphone && k == 127)) { - var pos = this.caret(), - begin = pos.begin, - end = pos.end; - - if (end - begin === 0) { - begin = k != 46 ? this.seekPrev(begin) : (end = this.seekNext(begin - 1)); - end = k == 46 ? this.seekNext(end) : end; - } - - this.clearBuffer(begin, end); - this.shiftL(begin, end - 1); - - return false; - - // escape - } else if (k == 27) { - this.$phoneField.val(this.focusText); - this.caret(0, this.checkVal()); - - return false; - } - }, - - keypressEvent: function (e) { - var len = this.mask.length; - - var k = e.which, - pos = this.caret(); - - // Ignore - if (e.ctrlKey || e.altKey || e.metaKey || k < 32) { - return true; - - } else if (k) { - if (pos.end - pos.begin !== 0) { - this.clearBuffer(pos.begin, pos.end); - this.shiftL(pos.begin, pos.end - 1); - } - - var p = this.seekNext(pos.begin - 1); - - if (p < len) { - var c = String.fromCharCode(k); - - if (this.tests[p].test(c)) { - this.shiftR(p); - this.buffer[p] = c; - this.writeBuffer(); - var next = this.seekNext(p); - this.caret(next); - } - } - - return false; - } - }, - - pasteEvent: function () { - var that = this - - setTimeout(function () { - that.caret(that.checkVal(true)) - }, 0); - }, - - clearBuffer: function (start, end) { - var len = this.mask.length; - - for (var i = start; i < end && i < len; i++) { - if (this.tests[i]) { - this.buffer[i] = this.options.placeholder - } - } - }, - - writeBuffer: function () { - return this.$phoneField.val(this.buffer.join('')).val() - }, - - seekNext: function (pos) { - var len = this.mask.length; - - while (++pos <= len && !this.tests[pos]); - - return pos; - }, - - seekPrev: function (pos) { - while (--pos >= 0 && !this.tests[pos]); - - return pos; - }, - - shiftL: function (begin, end) { - var len = this.mask.length; - - if (begin < 0) return; - - for (var i = begin, j = this.seekNext(end); i < len; i++) { - if (this.tests[i]) { - if (j < len && this.tests[i].test(this.buffer[j])) { - this.buffer[i] = this.buffer[j]; - this.buffer[j] = this.options.placeholder; - - } else { - break; - } - - j = this.seekNext(j); - } - } - - this.writeBuffer(); - this.caret(Math.max(this.firstNonMaskPos, begin)); - }, - - shiftR: function (pos) { - var len = this.mask.length; - - for (var i = pos, c = this.options.placeholder; i < len; i++) { - if (this.tests[i]) { - var j = this.seekNext(i); - var t = this.buffer[i]; - - this.buffer[i] = c; - - if (j < len && this.tests[j].test(t)) { - c = t; - - } else { - break - } - } - } - } - }; - - /** - * Initialize form phone plugin - * - * @param {jQuery} $element - * @param {Object} options - */ - IPub.Forms.Phone.initialize = function ($element, options) { - $element.each(function () { - var $this = $(this); - - if (!$this.data('ipub-forms-phone')) { - $this.data('ipub-forms-phone', (new IPub.Forms.Phone($this, options).init())); - } - }); - }; - - /** - * Autoloading for form phone plugin - * - * @returns {jQuery} - */ - IPub.Forms.Phone.load = function () { - return $('[data-ipub-forms-phone]').ipubFormsPhone(); - }; - - /** - * IPub Forms phone plugin definition - */ - - var old = $.fn.ipubFormsPhone; - - $.fn.ipubFormsPhone = function (options) { - return this.each(function () { - var $this = $(this); - - if (!$this.data('ipub-forms-phone')) { - $this.data('ipub-forms-phone', (new IPub.Forms.Phone($this, options).init())); - } - }); - }; - - /** - * IPub Forms phone plugin no conflict - */ - - $.fn.ipubFormsPhone.noConflict = function () { - $.fn.ipubFormsPhone = old; - - return this; - }; - - /** - * IPub Forms phone plugin default settings - */ - - $.fn.ipubFormsPhone.defaults = { - mask: '', - placeholder: '_', - definitions: { - '9': '[0-9]', - 'a': '[A-Za-z]', - 'w': '[A-Za-z0-9]', - '*': '.' - } - }; - - /** - * Complete plugin - */ - - // Autoload plugin - IPub.Forms.Phone.load(); - - // Autoload for ajax calls - $(document).ajaxSuccess(function () { - // Autoload plugin - IPub.Forms.Phone.load(); - }); - - // Assign plugin data to DOM - window.IPub = IPub; - - return IPub; - -})(jQuery, window, document, location, navigator); - -/** - * IPub.forms.phone custom validator - * - * @param {obj} elem - * @param {Array} arg - * @param {String} value - */ -Nette.validators.IPubFormPhoneFormsPhoneValidator_validatePhone = function (elem, arg, value) { - if (value.trim() == '') return; - - // Validator params - var params = new Array; - - // Try to find country slect element - var countryFieldName = elem.name.substring(0, elem.name.lastIndexOf('[')) + '\[country\]'; - var countryField; - - // If country select element exists... - if (countryField = document.getElementsByName(countryFieldName)[0]) { - // ...get value for country check - params.push(countryField.value); - - // No country selected, set to automatic detection - } else { - params.push('AUTO'); - } - - // Try to validate field - return new IPub.Phone.Validator(elem, params).validate(); -}; diff --git a/public/readme.md b/public/readme.md index 3cfc49e..719aa86 100644 --- a/public/readme.md +++ b/public/readme.md @@ -1,28 +1,37 @@ ## Javascript API Documentation -API for Phone is accessible in global object `window.IPub.Forms.Phone`. +API for Slug is accessible in global object `window.IPub.Forms.Slug`. ### Loading -Server-side part of Phone form element is element with custom data attribute `data-ipub-forms-phone`. This element can be initialized with method `init()`. +Serverside part of Slug form element is element with custom data attribute `data-ipub-forms-slug`. This element can be initialized with method `initialize()`. ```js -var phone = new IPub.Forms.Phone($('[data-ipub-forms-phone]')); - phone.init(); +IPub.Forms.Slug.initialize($('[data-ipub-forms-slug]')); ``` But there is shortcut implemented as jQuery plugin: ```js -$('[data-ipub-forms-phone]').ipubFormsPhone(); +$('[data-ipub-forms-slug]').ipubFormsSlug(); ``` -You can chain other jQuery methods after this as usual. If you try to initialize one Phone twice, it will fail silently (second initialization won't proceed). +You can chain other jQuery methods after this as usual. If you try to initialize one Slug twice, it will fail silently (second initialization won't proceed). -Finally you can initialize phone field on the page by calling: +Finally you can initialize sluggable field on the page by calling: ```js -IPub.Forms.Phone.load(); +IPub.Forms.Slug.load(); ``` -This plugin is initialized automatically, so you don't need to add another calls, you just need to inject JS file into your page. +This will be automatically called when document is ready. + +### Change event + +You can listen to event, when slug is changed: + +```js +$('#foo').on('change.ipub.forms.slug', function (e, slug) { + console.log('new slug: ', slug); +}); +``` diff --git a/readme.md b/readme.md index b7d5c12..409e701 100644 --- a/readme.md +++ b/readme.md @@ -1,33 +1,33 @@ -# Form Phone control +# Form Slug control -[![Build Status](https://img.shields.io/travis/iPublikuj/form-phone.svg?style=flat-square)](https://travis-ci.org/iPublikuj/form-phone) -[![Scrutinizer Code Coverage](https://img.shields.io/scrutinizer/coverage/g/iPublikuj/form-phone.svg?style=flat-square)](https://scrutinizer-ci.com/g/iPublikuj/form-phone/?branch=master) -[![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/g/iPublikuj/form-phone.svg?style=flat-square)](https://scrutinizer-ci.com/g/iPublikuj/form-phone/?branch=master) -[![Latest Stable Version](https://img.shields.io/packagist/v/ipub/form-phone.svg?style=flat-square)](https://packagist.org/packages/ipub/form-phone) -[![Composer Downloads](https://img.shields.io/packagist/dt/ipub/form-phone.svg?style=flat-square)](https://packagist.org/packages/ipub/form-phone) -[![License](https://img.shields.io/packagist/l/ipub/form-phone.svg?style=flat-square)](https://packagist.org/packages/ipub/form-phone) +[![Build Status](https://img.shields.io/travis/iPublikuj/form-slug.svg?style=flat-square)](https://travis-ci.org/iPublikuj/form-slug) +[![Scrutinizer Code Coverage](https://img.shields.io/scrutinizer/coverage/g/iPublikuj/form-slug.svg?style=flat-square)](https://scrutinizer-ci.com/g/iPublikuj/form-slug/?branch=master) +[![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/g/iPublikuj/form-slug.svg?style=flat-square)](https://scrutinizer-ci.com/g/iPublikuj/form-slug/?branch=master) +[![Latest Stable Version](https://img.shields.io/packagist/v/ipub/form-slug.svg?style=flat-square)](https://packagist.org/packages/ipub/form-slug) +[![Composer Downloads](https://img.shields.io/packagist/dt/ipub/form-slug.svg?style=flat-square)](https://packagist.org/packages/ipub/form-slug) +[![License](https://img.shields.io/packagist/l/ipub/form-slug.svg?style=flat-square)](https://packagist.org/packages/ipub/form-slug) -Forms control for adding phone number filed for [Nette Framework](http://nette.org/) +Forms control for adding slug filed for [Nette Framework](http://nette.org/) ## Installation -The best way to install ipub/form-phone is using [Composer](http://getcomposer.org/): +The best way to install ipub/form-slug is using [Composer](http://getcomposer.org/): ```sh -$ composer require ipub/form-phone +$ composer require ipub/form-slug:@dev ``` After that you have to register extension in config.neon. ```neon extensions: - formPhone: IPub\FormPhone\DI\FormPhoneExtension + formSlug: IPub\FormSlug\DI\FormSlugExtension ``` And you also need to include static files into your page: ```html - + ``` @@ -35,8 +35,8 @@ note: You have to upload static files from **client-site** folder to your projec ## Documentation -Learn how to extend your forms with phone field in [documentation](https://github.com/iPublikuj/form-phone/blob/master/docs/en/index.md). -For JavaScript part of this extension please checkout [JS documentation](https://github.com/iPublikuj/form-phone/blob/master/public/readme.md) +Learn how to extend your forms with phone field in [documentation](https://github.com/iPublikuj/form-slug/blob/master/docs/en/index.md). +For JavaScript part of this extension please checkout [JS documentation](https://github.com/iPublikuj/form-slug/blob/master/public/readme.md) *** -Homepage [http://www.ipublikuj.eu](http://www.ipublikuj.eu) and repository [http://github.com/iPublikuj/form-phone](http://github.com/iPublikuj/form-phone). +Homepage [http://www.ipublikuj.eu](http://www.ipublikuj.eu) and repository [http://github.com/iPublikuj/form-slug](http://github.com/iPublikuj/form-slug). diff --git a/src/IPub/FormPhone/Controls/Phone.php b/src/IPub/FormPhone/Controls/Phone.php deleted file mode 100644 index 9f83a5c..0000000 --- a/src/IPub/FormPhone/Controls/Phone.php +++ /dev/null @@ -1,522 +0,0 @@ - - * @package iPublikuj:FormPhone! - * @subpackage Controls - * @since 1.0.0 - * - * @date 15.12.15 - */ - -declare(strict_types = 1); - -namespace IPub\FormPhone\Controls; - -use Nette; -use Nette\Forms; -use Nette\Localization; -use Nette\Utils; - -use IPub; -use IPub\FormPhone; -use IPub\FormPhone\Exceptions; - -use IPub\Phone\Phone as PhoneUtils; - -use libphonenumber; - -/** - * Form phone control element - * - * @package iPublikuj:FormPhone! - * @subpackage Controls - * - * @author Adam Kadlec - * - * @property-read string $emptyValue - * @property-read Nette\Forms\Rules $rules - */ -class Phone extends Forms\Controls\TextInput -{ - /** - * Define filed attributes - */ - const FIELD_COUNTRY = 'country'; - const FIELD_NUMBER = 'number'; - - /** - * @var IPub\Phone\Phone - */ - private $phoneUtils; - - /** - * List of allowed countries - * - * @var array - */ - private $allowedCountries = []; - - /** - * List of allowed phone types - * - * @var array - */ - private $allowedTypes = []; - - /** - * @var string|NULL - */ - private $number = NULL; - - /** - * @var string|NULL - */ - private $country = NULL; - - /** - * @var string - */ - private $defaultCountry; - - /** - * @var bool - */ - private static $registered = FALSE; - - /** - * @param PhoneUtils $phoneUtils - * @param string|NULL $label - * @param int|NULL $maxLength - */ - public function __construct(PhoneUtils $phoneUtils, string $label = NULL, int $maxLength = NULL) - { - parent::__construct($label, $maxLength); - - $this->phoneUtils = $phoneUtils; - } - - /** - * @param array $countries - * - * @return $this - * - * @throws Exceptions\NoValidCountryException - */ - public function setAllowedCountries(array $countries = []) - { - $this->allowedCountries = []; - - foreach ($countries as $country) { - $country = $this->validateCountry($country); - $this->allowedCountries[] = strtoupper($country); - } - - // Check for auto country detection - if (in_array('AUTO', $this->allowedCountries)) { - $this->allowedCountries = ['AUTO']; - } - - // Remove duplicities - array_unique($this->allowedCountries); - - return $this; - } - - /** - * @param string $country - * - * @return $this - * - * @throws Exceptions\NoValidCountryException - */ - public function addAllowedCountry(string $country) - { - $country = $this->validateCountry($country); - $this->allowedCountries[] = strtoupper($country); - - // Remove duplicities - array_unique($this->allowedCountries); - - if (strtoupper($country) === 'AUTO') { - $this->allowedCountries = ['AUTO']; - - } elseif (($key = array_search('AUTO', $this->allowedCountries)) && $key !== FALSE) { - unset($this->allowedCountries[$key]); - } - - return $this; - } - - /** - * @return array - */ - public function getAllowedCountries() : array - { - if (in_array('AUTO', $this->allowedCountries, TRUE) || $this->allowedCountries === []) { - return $this->phoneUtils->getSupportedCountries(); - } - - return $this->allowedCountries; - } - - /** - * @param string|NULL $country - * - * @return $this - * - * @throws Exceptions\NoValidCountryException - */ - public function setDefaultCountry(string $country = NULL) - { - if ($country === NULL) { - $this->defaultCountry = NULL; - - } else { - $country = $this->validateCountry($country); - - $this->defaultCountry = strtoupper($country); - } - - return $this; - } - - /** - * @param array $types - * - * @return $this - * - * @throws Exceptions\NoValidTypeException - */ - public function setAllowedPhoneTypes(array $types = []) - { - $this->allowedTypes = []; - - foreach ($types as $type) { - $type = $this->validateType($type); - $this->allowedTypes[] = strtoupper($type); - } - - // Remove duplicities - array_unique($this->allowedTypes); - - return $this; - } - - /** - * @param string $type - * - * @return $this - * - * @throws Exceptions\NoValidTypeException - */ - public function addAllowedPhoneType(string $type) - { - $type = $this->validateType($type); - $this->allowedTypes[] = strtoupper($type); - - // Remove duplicities - array_unique($this->allowedTypes); - - return $this; - } - - /** - * @return array - */ - public function getAllowedPhoneTypes() : array - { - return $this->allowedTypes; - } - - /** - * @param string - * - * @return $this - * - * @throws Exceptions\InvalidArgumentException - * @throws IPub\Phone\Exceptions\NoValidCountryException - * @throws IPub\Phone\Exceptions\NoValidPhoneException - */ - public function setValue($value) - { - if ($value === NULL) { - $this->country = NULL; - $this->number = NULL; - - return $this; - } - - if ($value instanceof IPub\Phone\Entities\Phone) { - if (in_array($value->getCountry(), $this->getAllowedCountries(), TRUE)) { - $this->country = $value->getCountry(); - $this->number = str_replace(' ', '', $value->getNationalNumber()); - - return $this; - } - - } else { - foreach ($this->getAllowedCountries() as $country) { - if ($this->phoneUtils->isValid((string) $value, $country)) { - $phone = IPub\Phone\Entities\Phone::fromNumber((string) $value, $country); - - $this->country = $phone->getCountry(); - $this->number = str_replace(' ', '', $phone->getNationalNumber()); - - return $this; - } - } - } - - throw new Exceptions\InvalidArgumentException(sprintf('Provided value is not valid phone number, or is out of list of allowed countries, "%s" given.', $value)); - } - - /** - * @param string $key - * - * @return string - * - * @throws Exceptions\InvalidArgumentException - */ - public function getValuePart(string $key) : string - { - if ($key === self::FIELD_COUNTRY) { - return $this->country; - - } elseif ($key === self::FIELD_NUMBER) { - return $this->number; - } - - throw new Exceptions\InvalidArgumentException('Invalid field key provided.'); - } - - /** - * @return IPub\Phone\Entities\Phone|NULL|FALSE - */ - public function getValue() - { - if ($this->country === NULL || $this->number === NULL) { - return NULL; - } - - try { - // Try to parse number & country - return IPub\Phone\Entities\Phone::fromNumber($this->number, $this->country); - - } catch (IPub\Phone\Exceptions\NoValidCountryException $ex) { - return FALSE; - - } catch (IPub\Phone\Exceptions\NoValidPhoneException $ex) { - return FALSE; - } - } - - /** - * Loads HTTP data - * - * @return void - */ - public function loadHttpData() - { - $country = $this->getHttpData(Forms\Form::DATA_LINE, '[' . self::FIELD_COUNTRY . ']'); - $this->country = ($country === '' || $country === NULL) ? NULL : (string) $country; - - $number = $this->getHttpData(Forms\Form::DATA_LINE, '[' . self::FIELD_NUMBER . ']'); - $this->number = ($number === '' || $number === NULL) ? NULL : (string) $number; - } - - /** - * @return Utils\Html - */ - public function getControl() - { - $el = Utils\Html::el(); - $el->addHtml($this->getControlPart(self::FIELD_COUNTRY) . $this->getControlPart(self::FIELD_NUMBER)); - - return $el; - } - - /** - * @return Utils\Html - * - * @throws Exceptions\InvalidArgumentException - */ - public function getControlPart() - { - $args = func_get_args(); - $key = reset($args); - - $name = $this->getHtmlName(); - - if ($key === self::FIELD_COUNTRY) { - // Try to get translator - $translator = $this->getTranslator(); - - $locale = 'en_US'; - - if ($translator instanceof Localization\ITranslator && method_exists($translator, 'getLocale') === TRUE) { - try { - $locale = $translator->getLocale(); - - } catch (\Exception $ex) { - $locale = 'en_US'; - } - } - - $items = array_reduce($this->getAllowedCountries(), function (array $result, $row) use ($locale) { - $countryName = FormPhone\Locale\Locale::getDisplayRegion( - FormPhone\Locale\Locale::countryCodeToLocale($row), - $locale - ); - - $result[$row] = Utils\Html::el('option'); - $result[$row]->setText('+' . $this->phoneUtils->getCountryCodeForCountry($row) . ' (' . $countryName . ')'); - $result[$row]->data('mask', preg_replace('/[0-9]/', '9', $this->phoneUtils->getExampleNationalNumber($row))); - $result[$row]->addAttributes([ - 'value' => $row, - ]); - - return $result; - }, []); - - $control = Forms\Helpers::createSelectBox( - $items, - [ - 'selected?' => $this->country === NULL ? $this->defaultCountry : $this->country, - ] - ); - - $control->addAttributes([ - 'name' => $name . '[' . self::FIELD_COUNTRY . ']', - 'id' => $this->getHtmlId() . '-' . self::FIELD_COUNTRY, - ]); - $control->data('ipub-forms-phone', ''); - $control->data('settings', json_encode([ - 'field' => $name . '[' . self::FIELD_NUMBER . ']' - ]) - ); - - if ($this->isDisabled()) { - $control->addAttributes([ - 'disabled' => TRUE, - ]); - } - - return $control; - - } elseif ($key === self::FIELD_NUMBER) { - $prototype = $this->getControlPrototype(); - - $input = parent::getControl(); - - $control = Utils\Html::el('input'); - - $control->addAttributes([ - 'name' => $name . '[' . self::FIELD_NUMBER . ']', - 'id' => $this->getHtmlId() . '-' . self::FIELD_NUMBER, - 'value' => $this->number, - 'type' => 'text', - 'class' => $prototype->getAttribute('class'), - ]); - - $control->data('nette-empty-value', Utils\Strings::trim($this->translate($this->emptyValue))); - $control->data('nette-rules', $input->{'data-nette-rules'}); - - if ($this->isDisabled()) { - $control->addAttributes([ - 'disabled' => TRUE, - ]); - } - - return $control; - } - - throw new Exceptions\InvalidArgumentException(sprintf('Part "%s" does not exist.', $key)); - } - - /** - * {@inheritdoc} - */ - public function getLabel($caption = NULL) - { - $label = parent::getLabel($caption); - $label->for = $this->getHtmlId() . '-' . self::FIELD_NUMBER; - - return $label; - } - - /** - * {@inheritdoc} - */ - public function getLabelPart() - { - return NULL; - } - - /** - * @param string $country - * - * @return string - * - * @throws Exceptions\NoValidCountryException - */ - private function validateCountry(string $country) : string - { - // Country code have to be upper-cased - $country = strtoupper($country); - - if ((strlen($country) === 2 && ctype_alpha($country) && ctype_upper($country) && in_array($country, $this->phoneUtils->getSupportedCountries())) || $country === 'AUTO') { - return $country; - - } else { - throw new Exceptions\NoValidCountryException(sprintf('Provided country code "%s" is not valid. Provide valid country code or AUTO for automatic detection.', $country)); - } - } - - /** - * @param string $type - * - * @return string - * - * @throws Exceptions\NoValidTypeException - */ - private function validateType(string $type) : string - { - // Phone type have to be upper-cased - $type = strtoupper($type); - - if (defined('\IPub\Phone\Phone::TYPE_' . $type)) { - return $type; - - } else { - throw new Exceptions\NoValidTypeException(sprintf('Provided phone type "%s" is not valid. Provide valid phone type.', $type)); - } - } - - /** - * @param PhoneUtils $phoneUtils - * @param string $method - */ - public static function register(PhoneUtils $phoneUtils, string $method = 'addPhone') - { - // Check for multiple registration - if (self::$registered) { - throw new Nette\InvalidStateException('Phone control already registered.'); - } - - self::$registered = TRUE; - - $class = function_exists('get_called_class') ? get_called_class() : __CLASS__; - Forms\Container::extensionMethod( - $method, function (Forms\Container $form, $name, $label = NULL, $maxLength = NULL) use ($class, $phoneUtils) { - $component = new $class($phoneUtils, $label, $maxLength); - $form->addComponent($component, $name); - - return $component; - } - ); - } -} diff --git a/src/IPub/FormPhone/DI/FormPhoneExtension.php b/src/IPub/FormPhone/DI/FormPhoneExtension.php deleted file mode 100644 index 3641c7a..0000000 --- a/src/IPub/FormPhone/DI/FormPhoneExtension.php +++ /dev/null @@ -1,51 +0,0 @@ - - * @package iPublikuj:FormPhone! - * @subpackage DI - * @since 1.0.0 - * - * @date 15.12.15 - */ - -declare(strict_types = 1); - -namespace IPub\FormPhone\DI; - -use Nette; -use Nette\DI; -use Nette\PhpGenerator as Code; - -use IPub; -use IPub\Phone; - -/** - * Form phone control extension container - * - * @package iPublikuj:FormPhone! - * @subpackage DI - * - * @author Adam Kadlec - */ -final class FormPhoneExtension extends DI\CompilerExtension -{ - /** - * {@inheritdoc} - */ - public function afterCompile(Code\ClassType $class) - { - parent::afterCompile($class); - - $builder = $this->getContainerBuilder(); - - /** @var Code\Method $initialize */ - $initialize = $class->methods['initialize']; - $initialize->addBody('IPub\FormPhone\Controls\Phone::register($this->getService(?));', [ - $builder->getByType(Phone\Phone::class) - ]); - } -} diff --git a/src/IPub/FormPhone/Exceptions/IException.php b/src/IPub/FormPhone/Exceptions/IException.php deleted file mode 100644 index 4ff2b40..0000000 --- a/src/IPub/FormPhone/Exceptions/IException.php +++ /dev/null @@ -1,21 +0,0 @@ - - * @package iPublikuj:FormPhone! - * @subpackage Exceptions - * @since 1.0.0 - * - * @date 17.12.15 - */ - -declare(strict_types = 1); - -namespace IPub\FormPhone\Exceptions; - -interface IException -{ -} diff --git a/src/IPub/FormPhone/Exceptions/InvalidArgumentException.php b/src/IPub/FormPhone/Exceptions/InvalidArgumentException.php deleted file mode 100644 index ad86706..0000000 --- a/src/IPub/FormPhone/Exceptions/InvalidArgumentException.php +++ /dev/null @@ -1,21 +0,0 @@ - - * @package iPublikuj:FormPhone! - * @subpackage Exceptions - * @since 1.0.0 - * - * @date 17.12.15 - */ - -declare(strict_types = 1); - -namespace IPub\FormPhone\Exceptions; - -class InvalidArgumentException extends \InvalidArgumentException implements IException -{ -} diff --git a/src/IPub/FormPhone/Exceptions/NoValidCountryException.php b/src/IPub/FormPhone/Exceptions/NoValidCountryException.php deleted file mode 100644 index 7e72e83..0000000 --- a/src/IPub/FormPhone/Exceptions/NoValidCountryException.php +++ /dev/null @@ -1,21 +0,0 @@ - - * @package iPublikuj:FormPhone! - * @subpackage Exceptions - * @since 1.0.0 - * - * @date 17.12.15 - */ - -declare(strict_types = 1); - -namespace IPub\FormPhone\Exceptions; - -class NoValidCountryException extends \Exception -{ -} diff --git a/src/IPub/FormPhone/Exceptions/NoValidTypeException.php b/src/IPub/FormPhone/Exceptions/NoValidTypeException.php deleted file mode 100644 index b122ddf..0000000 --- a/src/IPub/FormPhone/Exceptions/NoValidTypeException.php +++ /dev/null @@ -1,21 +0,0 @@ - - * @package iPublikuj:FormPhone! - * @subpackage Exceptions - * @since 1.0.0 - * - * @date 19.12.15 - */ - -declare(strict_types = 1); - -namespace IPub\FormPhone\Exceptions; - -class NoValidTypeException extends \Exception -{ -} diff --git a/src/IPub/FormPhone/Forms/PhoneValidator.php b/src/IPub/FormPhone/Forms/PhoneValidator.php deleted file mode 100644 index 49c90f8..0000000 --- a/src/IPub/FormPhone/Forms/PhoneValidator.php +++ /dev/null @@ -1,126 +0,0 @@ - - * @package iPublikuj:FormPhone! - * @subpackage Forms - * @since 1.0.0 - * - * @date 12.12.15 - */ - -declare(strict_types = 1); - -namespace IPub\FormPhone\Forms; - -use Nette; -use Nette\Forms; - -use libphonenumber; -use libphonenumber\PhoneNumberUtil; - -use IPub\FormPhone; -use IPub\FormPhone\Controls; -use IPub\FormPhone\Exceptions; - -use IPub\Phone; -use Tracy\Debugger; - -/** - * Phone number control form field validator - * - * @package iPublikuj:FormPhone! - * @subpackage Forms - * - * @author Adam Kadlec - */ -class PhoneValidator extends Phone\Forms\PhoneValidator -{ - /** - * Define validator calling constant - */ - const PHONE = 'IPub\FormPhone\Forms\PhoneValidator::validatePhone'; - - /** - * @param Forms\IControl $control - * @param array|NULL $params - * - * @return bool - * - * @throws Exceptions\NoValidCountryException - */ - public static function validatePhone(Forms\IControl $control, $params = []) : bool - { - if (!$control instanceof Controls\Phone) { - throw new Exceptions\InvalidArgumentException(sprintf('This validator could be used only on text field. You used it on: "%s"', get_class($control))); - } - - if ($control->getValuePart(Controls\Phone::FIELD_NUMBER) === NULL || $control->getValuePart(Controls\Phone::FIELD_COUNTRY) === NULL) { - return TRUE; - } - - try { - // Create phone entity - $value = Phone\Entities\Phone::fromNumber($control->getValuePart(Controls\Phone::FIELD_NUMBER), $control->getValuePart(Controls\Phone::FIELD_COUNTRY)); - - } catch (Phone\Exceptions\NoValidCountryException $ex) { - return FALSE; - - } catch (Phone\Exceptions\NoValidPhoneException $ex) { - return FALSE; - } - - // Value have to be phone entity - if ($value instanceof Phone\Entities\Phone) { - $number = $value->getRawOutput(); - - // Get instance of phone number util - $phoneNumberUtil = PhoneNumberUtil::getInstance(); - - // Get list of allowed countries from params - $allowedCountries = self::determineCountries($control->getAllowedCountries()); - - // Get list of allowed phone types - $allowedTypes = self::determineTypes($control->getAllowedPhoneTypes()); - - // Perform validation - foreach ($allowedCountries as $country) { - try { - // For default countries or country field, the following throws NumberParseException if - // not parsed correctly against the supplied country - // For automatic detection: tries to discover the country code using from the number itself - $phoneProto = $phoneNumberUtil->parse($number, $country); - - // For automatic detection, the number should have a country code - // Check if type is allowed - if ( - $phoneProto->hasCountryCode() && - $allowedTypes === [] || - in_array($phoneNumberUtil->getNumberType($phoneProto), $allowedTypes) - ) { - // Automatic detection: - if ($country == 'ZZ') { - // Validate if the international phone number is valid for its contained country - return $phoneNumberUtil->isValidNumber($phoneProto); - } - - // Validate number against the specified country. Return only if success - // If failure, continue loop to next specified country - if ($phoneNumberUtil->isValidNumberForRegion($phoneProto, $country)) { - return TRUE; - } - } - - } catch (libphonenumber\NumberParseException $ex) { - // Proceed to default validation error - } - } - } - - // All specified country validations have failed - return FALSE; - } -} diff --git a/src/IPub/FormPhone/Locale/Locale.php b/src/IPub/FormPhone/Locale/Locale.php deleted file mode 100644 index afa7a00..0000000 --- a/src/IPub/FormPhone/Locale/Locale.php +++ /dev/null @@ -1,55 +0,0 @@ - - * @package iPublikuj:FormPhone! - * @subpackage Locale - * @since 1.0.4 - * - * @date 20.08.16 - */ - -declare(strict_types = 1); - -namespace IPub\FormPhone\Locale; - -use Giggsey; - -/** - * Locale helper - * - * @package iPublikuj:FormPhone! - * @subpackage Locale - * - * @author Adam Kadlec - */ -class Locale extends Giggsey\Locale\Locale -{ - /** - * @link http://stackoverflow.com/a/10375234/403165 - * - * @param string $countryCode - * @param string $languageCode - * - * @return string|NULL - */ - public static function countryCodeToLocale(string $countryCode, string $languageCode = '') - { - $locale = 'en-' . $countryCode; - $localeRegion = locale_get_region($locale); - $localeLanguage = locale_get_primary_language($locale); - $localeArray = [ - 'language' => $localeLanguage, - 'region' => $localeRegion, - ]; - - if (strtoupper($countryCode) === $localeRegion && ($languageCode === '' || strtolower($languageCode) === $localeLanguage)) { - return locale_compose($localeArray); - } - - return NULL; - } -} diff --git a/tests/IPubTests/FormPhone/PhoneInputTest.phpt b/tests/IPubTests/FormPhone/PhoneInputTest.phpt deleted file mode 100644 index 58b5c8a..0000000 --- a/tests/IPubTests/FormPhone/PhoneInputTest.phpt +++ /dev/null @@ -1,395 +0,0 @@ - - */ -class PhoneInputTest extends Tester\TestCase -{ - /** - * @var Phone\Phone - */ - private $phone; - - /** - * @return array[]|array - */ - public function dataValidPhoneNumbers() : array - { - return [ - ['+1-734-555-1212', '+17345551212'], - ['+420234567890', '+420234567890'], - ['234 567 890', '+420234567890'], - ['+420.234.567.890', '+420234567890'], - ['+420-234-567-890', '+420234567890'], - ['00420234567890', '+420234567890'], - ['420234567890', '+420234567890'], - [420234567890, '+420234567890'], - ]; - } - - /** - * @return array[]|array - */ - public function dataInvalidPhoneNumbers() : array - { - return [ - ['foo'], - ['123'], - [123], - ['+1@800@692@7753'], - ]; - } - - /** - * @return array[]|array - */ - public function dataEmptyPhoneNumbers() : array - { - return [ - [NULL, NULL], - ]; - } - - /** - * @return array[]|array - */ - public function dataAllowedCountries() : array - { - return [ - [['CZ', 'SK'], ['CZ', 'SK']], - [['US'], ['US']], - ]; - } - - /** - * @return array[]|array - */ - public function dataInvalidAllowedCountries() : array - { - return [ - [['CZ', 'SK', 'XY'], ['CZ', 'SK', 'XY']], - [['US', 'XY'], ['US', 'XY']], - [['XY'], ['XY']], - ]; - } - - /** - * {@inheritdoc} - */ - public function setUp() - { - parent::setUp(); - - $dic = $this->createContainer(); - - // Get phone helper from container - $this->phone = $dic->getByType(Phone\Phone::class); - } - - /** - * @dataProvider dataValidPhoneNumbers - * - * @param string - * @param string - */ - public function testValidPhoneNumbers($input, $expected) - { - // Create form control - $control = new FormPhone\Controls\Phone($this->phone); - $control->setAllowedCountries(['CZ', 'US']); - $control->setValue($input); - - Assert::type('IPub\Phone\Entities\Phone', $control->getValue()); - Assert::equal($expected, $control->getValue()->getRawOutput()); - } - - /** - * @dataProvider dataInvalidPhoneNumbers - * - * @param string - */ - public function testInvalidPhoneNumbers($input) - { - // Create form control - $control = new FormPhone\Controls\Phone($this->phone); - $control->setAllowedCountries(['CZ', 'US']); - - Assert::exception(function() use ($control, $input) { - $control->setValue($input); - }, 'IPub\FormPhone\Exceptions\InvalidArgumentException'); - } - - /** - * @dataProvider dataEmptyPhoneNumbers - * - * @param string - * @param string - */ - public function testEmptyPhoneNumbers($input, $expected) - { - // Create form control - $control = new FormPhone\Controls\Phone($this->phone); - $control->setAllowedCountries(['CZ', 'US']); - $control->setValue($input); - - Assert::equal($expected, $control->getValue()); - } - - /** - * @dataProvider dataAllowedCountries - * - * @param string - * @param string - */ - public function testSetAllowedCountries($input, $expected) - { - // Create form control - $control = new FormPhone\Controls\Phone($this->phone); - $control->setAllowedCountries($input); - - Assert::equal($expected, $control->getAllowedCountries()); - } - - /** - * @dataProvider dataInvalidAllowedCountries - * - * @param string - * @param string - */ - public function testSetInvalidAllowedCountries($input, $expected) - { - // Create form control - $control = new FormPhone\Controls\Phone($this->phone); - - Assert::exception(function() use ($control, $input) { - $control->setAllowedCountries($input); - }, 'IPub\FormPhone\Exceptions\NoValidCountryException'); - } - - public function testDefaultCountry() - { - // Create form control - $control = $this->createControl(); - - $dq = Tester\DomQuery::fromHtml((string) $control->getControlPart(FormPhone\Controls\Phone::FIELD_COUNTRY)); - Assert::false($dq->has('select option[selected]')); - - // Define default country - $control->setDefaultCountry('CZ'); - - $dq = Tester\DomQuery::fromHtml((string) $control->getControlPart(FormPhone\Controls\Phone::FIELD_COUNTRY)); - - Assert::true($dq->has('select option[selected]')); - Assert::true($dq->has('select option[value=CZ][selected]')); - - // Define default country - $control->setDefaultCountry(NULL); - - $dq = Tester\DomQuery::fromHtml((string) $control->getControlPart(FormPhone\Controls\Phone::FIELD_COUNTRY)); - Assert::false($dq->has('select option[selected]')); - } - - public function testInvalidDefaultCountry() - { - // Create form control - $control = $this->createControl(); - - Assert::exception(function() use ($control) { - $control->setDefaultCountry('xy'); - }, 'IPub\FormPhone\Exceptions\NoValidCountryException'); - - Assert::exception(function() use ($control) { - $control->setDefaultCountry('CZE'); - }, 'IPub\FormPhone\Exceptions\NoValidCountryException'); - } - - public function testHtmlPartNumber() - { - // Create form - $form = new Forms\Form; - // Create form control - $control = new FormPhone\Controls\Phone($this->phone); - // Add form control to form - $form->addComponent($control, 'phone'); - - // Set some value - $control->setValue('+420234567890'); - - $dq = Tester\DomQuery::fromHtml((string) $control->getControlPart(FormPhone\Controls\Phone::FIELD_NUMBER)); - - Assert::true($dq->has('input[value=234567890]')); - } - - public function testHtmlPartCountry() - { - // Create form - $form = new Forms\Form; - // Create form control - $control = new FormPhone\Controls\Phone($this->phone); - // Add form control to form - $form->addComponent($control, 'phone'); - - // Set some value - $control->setValue('+420234567890'); - - $dq = Tester\DomQuery::fromHtml((string) $control->getControlPart(FormPhone\Controls\Phone::FIELD_COUNTRY)); - - Assert::true($dq->has('select option[value=CZ][selected]')); - } - - public function testHtml() - { - // Create form - $form = new Forms\Form; - // Create form control - $control = new FormPhone\Controls\Phone($this->phone); - // Add form control to form - $form->addComponent($control, 'phone'); - - // Set some value - $control->setValue('+420234567890'); - - $dq = Tester\DomQuery::fromHtml((string) $control->getControl()); - - Assert::true($dq->has('input[value=234567890]')); - Assert::true($dq->has('select option[value=CZ][selected]')); - } - - public function testHtmlPartLabel() - { - // Create form - $form = new Forms\Form; - // Create form control - $control = new FormPhone\Controls\Phone($this->phone); - // Add form control to form - $form->addComponent($control, 'phone'); - - Assert::null($control->getLabelPart()); - } - - public function testLoadHttpDataEmpty() - { - // Create form control - $control = $this->createControl(); - - Assert::false($control->isFilled()); - Assert::null($control->getValue()); - } - - public function testLoadHttpDataValid() - { - // Create form control - $control = $this->createControl([ - 'phone' => [FormPhone\Controls\Phone::FIELD_COUNTRY => 'CZ', FormPhone\Controls\Phone::FIELD_NUMBER => '234567890'], - ]); - - Assert::type('IPub\Phone\Entities\Phone', $control->getValue()); - Assert::equal('+420234567890', $control->getValue()->getRawOutput()); - } - - public function testLoadHttpDataInvalid() - { - // Create form control - $control = $this->createControl([ - 'phone' => [FormPhone\Controls\Phone::FIELD_COUNTRY => NULL, FormPhone\Controls\Phone::FIELD_NUMBER => '123'], - ]); - - Assert::false($control->isFilled()); - Assert::null($control->getValue()); - } - - /** - * @throws Nette\InvalidStateException - */ - public function testRegistrationMultiple() - { - FormPhone\Controls\Phone::register($this->phone); - FormPhone\Controls\Phone::register($this->phone); - } - - public function testRegistration() - { - FormPhone\Controls\Phone::register($this->phone); - - // Create form - $form = new Forms\Form; - // Create form control - $control = $form->addPhone('phone', 'Phone number'); - - Assert::type('IPub\FormPhone\Controls\Phone', $control); - Assert::equal('phone', $control->getName()); - Assert::equal('Phone number', $control->caption); - Assert::same($form, $control->getForm()); - } - - /** - * @param array $data - * - * @return FormPhone\Controls\Phone - */ - private function createControl(array $data = []) : FormPhone\Controls\Phone - { - $_SERVER['REQUEST_METHOD'] = 'POST'; - $_FILES = []; - $_POST = $data; - - // Create form - $form = new Forms\Form; - // Create form control - $control = new FormPhone\Controls\Phone($this->phone); - // Add form control to form - $form->addComponent($control, 'phone'); - - return $control; - } - - /** - * @return Nette\DI\Container - */ - protected function createContainer() : Nette\DI\Container - { - $config = new Nette\Configurator(); - $config->setTempDirectory(TEMP_DIR); - - $config->addConfig(__DIR__ . DS . 'files' . DS . 'config.neon'); - - return $config->createContainer(); - } -} - -\run(new PhoneInputTest()); diff --git a/tests/IPubTests/FormPhone/PhoneValidationTest.phpt b/tests/IPubTests/FormPhone/PhoneValidationTest.phpt deleted file mode 100644 index b23312b..0000000 --- a/tests/IPubTests/FormPhone/PhoneValidationTest.phpt +++ /dev/null @@ -1,308 +0,0 @@ - - */ -class PhoneValidationTest extends Tester\TestCase -{ - /** - * @var Phone\Phone - */ - private $phone; - - /** - * {@inheritdoc} - */ - public function setUp() - { - parent::setUp(); - - $dic = $this->createContainer(); - - // Get phone helper from container - $this->phone = $dic->getByType(Phone\Phone::class); - } - - public function testValidatePhoneWithDefaultCountryWithoutType() - { - // Validator with correct country value - $field = $this->createControl([ - 'phone' => [FormPhone\Controls\Phone::FIELD_COUNTRY => 'BE', FormPhone\Controls\Phone::FIELD_NUMBER => '016123456'], - ]); - // Set allowed country - $field->addAllowedCountry('BE'); - $field - ->addRule(FormPhone\Forms\PhoneValidator::PHONE, 'Invalid phone') - ->validate(); - - Assert::false($field->hasErrors()); - - // Validator with wrong country value - $field = $this->createControl([ - 'phone' => [FormPhone\Controls\Phone::FIELD_COUNTRY => 'NL', FormPhone\Controls\Phone::FIELD_NUMBER => '016123456'], - ]); - // Set allowed country - $field->addAllowedCountry('NL'); - $field - ->addRule(FormPhone\Forms\PhoneValidator::PHONE, 'Invalid phone') - ->validate(); - - Assert::true($field->hasErrors()); - - // Validator with multiple country values, one correct - $field = $this->createControl([ - 'phone' => [FormPhone\Controls\Phone::FIELD_COUNTRY => 'BE', FormPhone\Controls\Phone::FIELD_NUMBER => '016123456'], - ]); - // Set allowed country - $field->setAllowedCountries(['BE', 'NL']); - $field - ->addRule(FormPhone\Forms\PhoneValidator::PHONE, 'Invalid phone') - ->validate(); - - Assert::false($field->hasErrors()); - - // Validator with multiple wrong country values - $field = $this->createControl([ - 'phone' => [FormPhone\Controls\Phone::FIELD_COUNTRY => 'DE', FormPhone\Controls\Phone::FIELD_NUMBER => '016123456'], - ]); - // Set allowed country - $field->setAllowedCountries(['DE', 'NL']); - $field - ->addRule(FormPhone\Forms\PhoneValidator::PHONE, 'Invalid phone') - ->validate(); - - Assert::true($field->hasErrors()); - - // Validator with multiple wrong country values - $field = $this->createControl([ - 'phone' => [FormPhone\Controls\Phone::FIELD_COUNTRY => 'DE', FormPhone\Controls\Phone::FIELD_NUMBER => '016123456'], - ]); - // Set allowed country - $field->setAllowedCountries(['BE', 'DE', 'NL']); - $field - ->addRule(FormPhone\Forms\PhoneValidator::PHONE, 'Invalid phone') - ->validate(); - - Assert::true($field->hasErrors()); - } - - public function testValidatePhoneWithDefaultCountryWithType() - { - // Validator with correct country value, correct type - $field = $this->createControl([ - 'phone' => [FormPhone\Controls\Phone::FIELD_COUNTRY => 'BE', FormPhone\Controls\Phone::FIELD_NUMBER => '0499123456'], - ]); - // Set allowed country - $field->addAllowedCountry('BE'); - // Set allowed phone type - $field->addAllowedPhoneType('mobile'); - $field - ->addRule(FormPhone\Forms\PhoneValidator::PHONE, 'Invalid phone') - ->validate(); - - Assert::false($field->hasErrors()); - - // Validator with correct country value, wrong type - $field = $this->createControl([ - 'phone' => [FormPhone\Controls\Phone::FIELD_COUNTRY => 'BE', FormPhone\Controls\Phone::FIELD_NUMBER => '016123456'], - ]); - // Set allowed country - $field->addAllowedCountry('BE'); - // Set allowed phone type - $field->addAllowedPhoneType('mobile'); - $field - ->addRule(FormPhone\Forms\PhoneValidator::PHONE, 'Invalid phone') - ->validate(); - - Assert::true($field->hasErrors()); - - // Validator with wrong country value, correct type - $field = $this->createControl([ - 'phone' => [FormPhone\Controls\Phone::FIELD_COUNTRY => 'NL', FormPhone\Controls\Phone::FIELD_NUMBER => '0499123456'], - ]); - // Set allowed country - $field->addAllowedCountry('NL'); - // Set allowed phone type - $field->addAllowedPhoneType('mobile'); - $field - ->addRule(FormPhone\Forms\PhoneValidator::PHONE, 'Invalid phone') - ->validate(); - - Assert::true($field->hasErrors()); - - // Validator with wrong country value, wrong type - $field = $this->createControl([ - 'phone' => [FormPhone\Controls\Phone::FIELD_COUNTRY => 'NL', FormPhone\Controls\Phone::FIELD_NUMBER => '016123456'], - ]); - // Set allowed country - $field->addAllowedCountry('NL'); - // Set allowed phone type - $field->addAllowedPhoneType('mobile'); - $field - ->addRule(FormPhone\Forms\PhoneValidator::PHONE, 'Invalid phone') - ->validate(); - - Assert::true($field->hasErrors()); - - // Validator with multiple country values, one correct, correct type - $field = $this->createControl([ - 'phone' => [FormPhone\Controls\Phone::FIELD_COUNTRY => 'BE', FormPhone\Controls\Phone::FIELD_NUMBER => '0499123456'], - ]); - // Set allowed country - $field->setAllowedCountries(['BE', 'NL']); - // Set allowed phone type - $field->addAllowedPhoneType('mobile'); - $field - ->addRule(FormPhone\Forms\PhoneValidator::PHONE, 'Invalid phone') - ->validate(); - - Assert::false($field->hasErrors()); - - // Validator with multiple country values, one correct, wrong type - $field = $this->createControl([ - 'phone' => [FormPhone\Controls\Phone::FIELD_COUNTRY => 'BE', FormPhone\Controls\Phone::FIELD_NUMBER => '016123456'], - ]); - // Set allowed country - $field->setAllowedCountries(['BE', 'NL']); - // Set allowed phone type - $field->addAllowedPhoneType('mobile'); - $field - ->addRule(FormPhone\Forms\PhoneValidator::PHONE, 'Invalid phone') - ->validate(); - - Assert::true($field->hasErrors()); - - // Validator with multiple country values, none correct, correct type - $field = $this->createControl([ - 'phone' => [FormPhone\Controls\Phone::FIELD_COUNTRY => 'DE', FormPhone\Controls\Phone::FIELD_NUMBER => '0499123456'], - ]); - // Set allowed country - $field->setAllowedCountries(['DE', 'NL']); - // Set allowed phone type - $field->addAllowedPhoneType('mobile'); - $field - ->addRule(FormPhone\Forms\PhoneValidator::PHONE, 'Invalid phone') - ->validate(); - - Assert::true($field->hasErrors()); - - // Validator with multiple country values, none correct, wrong type - $field = $this->createControl([ - 'phone' => [FormPhone\Controls\Phone::FIELD_COUNTRY => 'DE', FormPhone\Controls\Phone::FIELD_NUMBER => '016123456'], - ]); - // Set allowed country - $field->setAllowedCountries(['DE', 'NL']); - // Set allowed phone type - $field->addAllowedPhoneType('mobile'); - $field - ->addRule(FormPhone\Forms\PhoneValidator::PHONE, 'Invalid phone') - ->validate(); - - Assert::true($field->hasErrors()); - } - - /** - * @throws \IPub\FormPhone\Exceptions\InvalidArgumentException - */ - public function testValidatorOnWrongControl() - { - // Validator with given country assigned to wrong control type - $field = $this->createInvalidControl(); - $field - ->addRule(FormPhone\Forms\PhoneValidator::PHONE, 'Invalid phone') - ->setValue('016123456') - ->validate(); - } - - /** - * @param array $data - * - * @return FormPhone\Controls\Phone - */ - private function createControl(array $data = []) : FormPhone\Controls\Phone - { - $_SERVER['REQUEST_METHOD'] = 'POST'; - $_FILES = []; - $_POST = $data; - - // Create form - $form = new Forms\Form; - // Create form control - $control = new FormPhone\Controls\Phone($this->phone); - // Add form control to form - $form->addComponent($control, 'phone'); - - return $control; - } - - /** - * @param array $data - * - * @return Forms\Controls\TextArea - */ - private function createInvalidControl(array $data = []) : Forms\Controls\TextArea - { - $_SERVER['REQUEST_METHOD'] = 'POST'; - $_FILES = []; - $_POST = $data; - - // Create form - $form = new Forms\Form; - // Create form control - $control = new Forms\Controls\TextArea; - // Add form control to form - $form->addComponent($control, 'phone'); - - return $control; - } - - /** - * @return Nette\DI\Container - */ - protected function createContainer() : Nette\DI\Container - { - $config = new Nette\Configurator(); - $config->setTempDirectory(TEMP_DIR); - - $config->addConfig(__DIR__ . DS . 'files' . DS . 'config.neon'); - - return $config->createContainer(); - } -} - -\run(new PhoneValidationTest()); diff --git a/tests/IPubTests/FormPhone/files/config.neon b/tests/IPubTests/FormPhone/files/config.neon deleted file mode 100644 index e55dae0..0000000 --- a/tests/IPubTests/FormPhone/files/config.neon +++ /dev/null @@ -1,3 +0,0 @@ -extensions: - phone : IPub\Phone\DI\PhoneExtension - diff --git a/tests/php.ini-unix b/tests/php.ini-unix index 7d3f769..e93a097 100644 --- a/tests/php.ini-unix +++ b/tests/php.ini-unix @@ -1,6 +1,4 @@ extension = xdebug.so -extension = intl.so -extension = json.so [xdebug] xdebug.enable = On diff --git a/tests/php.ini-win b/tests/php.ini-win index fc0aaa6..a6d494c 100644 --- a/tests/php.ini-win +++ b/tests/php.ini-win @@ -1,5 +1,3 @@ [PHP] extension_dir = "./ext" extension = php_xdebug.dll -extension = php_intl.dll -extension = php_json.dll