Skip to content

Commit

Permalink
Add word convertor
Browse files Browse the repository at this point in the history
  • Loading branch information
at-adoreme committed Jul 10, 2018
1 parent e23a187 commit 07630d5
Show file tree
Hide file tree
Showing 3 changed files with 262 additions and 18 deletions.
137 changes: 119 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,31 +7,132 @@

# README

## What is FileIo?
Common is a library packed with small re-usable utilities and helpers
## What is Common?
Common is a library packed with small re-usable utilities and helpers.

## Requirments
For larger usage, minimum version is PHP 5.5

## Instalation
Create/add to composer.json
```
{
"require": {
"needle-project/common": "dev-master"
},
"repositories": [
{
"type": "vcs",
"url": "https://github.com/needle-project/common"
}
]
```
composer require "needle-project/common"
```
## Content
1. WordType convertor - Converts string to `camelCase`, `PascalCase` or `snake_case`
2. ArrayHelper - searches if an array has a key in depth and retrieves the value
3. Error to Exception - convert php errors to Exceptions
4. ClassFinder - Searches for classes of a certain type.


### 1. WordType convertor
Converts a set of strings of typographical conventions between them.
It handles `camelCase`, `PascalCase` and `snake_case`.
**Usage**
```
<?php
require_once 'vendor/autoload.php';
use NeedleProject\Common\Convertor\CompoundWordConvertor;
echo CompoundWordConvertor::convertToPascalCase("Hello World") . "\n";
// HelloWorld
echo CompoundWordConvertor::convertToCamelCase("Hello World") . "\n";
// helloWorld
echo CompoundWordConvertor::convertToSnakeCase("Hello World") . "\n";
// hello_world
```
**Known issues**
Converting an already converted type will fail. Example:
```
<?php
require_once 'vendor/autoload.php';
use NeedleProject\Common\Convertor\CompoundWordConvertor;
echo CompoundWordConvertor::convertToCamelCase("fooBar");
// will output "foobar", not fooBar
echo CompoundWordConvertor::convertToPascalCase("FooBar");
// will output "Foobar", not FooBar
echo CompoundWordConvertor::convertToSnakeCase("FOO BAR");
// will output "f_o_o_b_a_r", not "foo_bar"
```
### 2. ArrayHelper
Searches for a key in depth and retrieves it or state it's presense.
**Usage**
```
<?php
require_once 'vendor/autoload.php';
use NeedleProject\Common\Helper\ArrayHelper;
$searchFor = ['level1', 'level2', 'level3'];
$searchIn = [
'level1' => [
'level2' => [
'level3' => 'A value'
]
]
];
$helper = new ArrayHelper();
if ($helper->hasKeysInDepth($searchIn, $searchFor)) {
echo $helper->getValueFromDepth($searchIn, $searchFor);
// A value
}
```
Afterwards run `composer install` or `composer update` depending on the context.
## 1.2. Cloning repository using git
### 3. Error to Exception
Converts a PHP error to an Exception.
Error level constans are the PHP's default ones that can be found [here](http://php.net/manual/ro/function.error-reporting.php "here").
```
git clone https://github.com/needle-project/common.git
<?php
require_once 'vendor/autoload.php';
use NeedleProject\Common\Util\ErrorToExceptionConverter;
class CustomException extends \Exception {
}
$convertor = new ErrorToExceptionConverter();
$convertor->convertErrorsToExceptions(E_ALL, CustomException::class);
try {
print(a);
} catch (\Exception $e) {
echo get_class($e) . "\n";
echo $e->getMessage();
}
// restore the previous state of error handling
$convertor->restoreErrorHandler();
```
### 4. ClassFinder
Searches for a class of a certain sub-type.
```
Run `composer install` in the library path.
<?php
require_once 'vendor/autoload.php';
use NeedleProject\Common\ClassFinder;
$classFinder = new ClassFinder(
__DIR__ . DIRECTORY_SEPARATOR . 'tests' . DIRECTORY_SEPARATOR . 'fixtures',
\Fixture\BaseInterface::class
);
$foundClasses = $classFinder->findClasses();
print_r($foundClasses);
php test.php
// Array
// (
// [0] => Fixture\Path\ClassList\BazClass
// [1] => Fixture\Path\ClassList\GodClass
// [2] => Fixture\Path\FooClass
// )
```
## Contribute
Feel free to contribute:
- State ideeas
- Open pull request with improvements/bug-fixes
61 changes: 61 additions & 0 deletions src/Convertor/CompoundWordConvertor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php
/**
* This file is part of the NeedleProject\Common package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace NeedleProject\Common\Convertor;

/**
* Class CompoundWordConvertor
*
* @package NeedleProject\Common\Convertor
* @author Adrian Tilita <adrian@tilita.ro>
* @copyright 2018 Adrian Tilita
* @license https://opensource.org/licenses/MIT MIT Licence
*/
class CompoundWordConvertor
{
/**
* Convert any string to camelCase
* @param string $word
* @return string
*/
public static function convertToCamelCase($word)
{
return lcfirst(self::convertToPascalCase($word));
}

/**
* Convert any string to PascalCase
* @param string $word
* @return string
*/
public static function convertToPascalCase($word)
{
// separate into block for easier readability
$word = str_replace('_', ' ', $word);
$word = strtolower($word);
$word = ucwords($word);
return str_replace(' ', '', $word);
}

/**
* Convert any string to underscore_string (snake_case)
* @param string $word
* @return string
*/
public static function convertToSnakeCase($word)
{
// append an _ to all capital letters. Ex: Abc will be converted to _Abc
$word = preg_replace('/(?<!^)[A-Z]/', '_$0', $word);
// replace spaces to underscore
$word = preg_replace('/\s/','_', $word);
// replace multiple spaces to one underscore
$word = preg_replace('/\s\s+/','_', $word);
// replace multiple underscores to one underscore
$word = preg_replace('/([_]+)/','_', $word);
return strtolower($word);
}
}
82 changes: 82 additions & 0 deletions tests/Convertor/CompoundWordConvertorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php
namespace NeedleProject\Common\Convertor;

use PHPUnit\Framework\TestCase;

class CompoundWordConvertorTest extends TestCase
{
/**
* @dataProvider provideCamelCaseScenarios
* @param $input
* @param $expectedOutput
*/
public function testConvertToCamelCase($input, $expectedOutput)
{
$this->assertEquals(
$expectedOutput,
CompoundWordConvertor::convertToCamelCase($input)
);
}

/**
* @dataProvider providePascalCaseScenarios
* @param $input
* @param $expectedOutput
*/
public function testConvertToPascalCase($input, $expectedOutput)
{
$this->assertEquals(
$expectedOutput,
CompoundWordConvertor::convertToPascalCase($input)
);
}

/**
* @dataProvider provideSnakeCaseScenarios
* @param $input
* @param $expectedOutput
*/
public function testConvertToSnakeCase($input, $expectedOutput)
{
$this->assertEquals(
$expectedOutput,
CompoundWordConvertor::convertToSnakeCase($input)
);
}

public function provideCamelCaseScenarios()
{
return [
['foo_bar', 'fooBar'],
['foo_a', 'fooA'],
['FOOO', 'fooo'],
['fOoOoOo BaRrRr', 'fooooooBarrrr'],
['Hello World', 'helloWorld']
// @needs a fix: ['fooBar', 'fooBar']
];
}

public function providePascalCaseScenarios()
{
return [
['foo_bar', 'FooBar'],
['foo_a', 'FooA'],
['FOOO', 'Fooo'],
['fOoOoOo BaRrRr', 'FooooooBarrrr'],
['Hello World', 'HelloWorld']
// @needs a fix: ['FooBar', 'FooBar']
];
}

public function provideSnakeCaseScenarios()
{
return [
['FooBar', 'foo_bar'],
['fooBarBaz', 'foo_bar_baz'],
['foo_bar', 'foo_bar'],
['Hello World', 'hello_world']
// @needs a fix: ['FOO BAR', 'foo_bar'],
// @needs a fix: ['SimpleXML', 'simple_xml']
];
}
}

0 comments on commit 07630d5

Please sign in to comment.