PHP Classes

Mapache Commons: Manipulate text, collections and debug PHP code

Recommend this page to a friend!
  Info   View files Example   View files View files (16)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
Not yet rated by the usersTotal: 36 This week: 1All time: 10,913 This week: 560Up
Version License PHP version Categories
mapache-commons 1.0GNU Lesser Genera...5PHP 5, Debug, Text processing, Data t...
Description 

Author

This package can be used to manipulate text, collections and debug PHP code.

It provides several classes that implement general purpose functions to do the following:

- Split a string by an opening and closing tag and returns an array with the result
- Split a string by ignoring parts of string where values are between " or '
- Change the case to lower or upper case of the keys of an array recursively
- Return the first or all the keys inside an array or object in an array that matches the value of the field
- Return true if an array is an associative array, false is it's an indexed array
- Returns the first element of an array
- Returns the first key of an array
- Change the case of all the keys to lower case or upper case
- Generate a html table from an array
- Dump variable values in Web pages or the console of JavaScript
- Write a log file and adds the text to the log
- Return an array with the name of the argument and value if any
- Return the first position of a string that it's not a space
- Return true if a string is completely in upper case or in lower case
- Return the text between two needles
- Replace the text between two needles
- Remove the first characters for a string
- Remove the last characters for a string
- Transform a text = 'a1=1,a2=2' into an associative array
- Parses a natural string and returns a declarative array
- Find the first or the last occurrence of a text

Picture of Jorge Castro
  Performance   Level  
Name: Jorge Castro <contact>
Classes: 30 packages by
Country: Chile Chile
Age: 48
All time rank: 12763 in Chile Chile
Week rank: 106 Up1 in Chile Chile Up
Innovation award
Innovation award
Nominee: 14x

Winner: 2x

Example

<?php

use mapache_commons\Collection;
use
mapache_commons\Debug;

include
"../lib/Collection.php";
include
"../lib/Debug.php";

$countries=array("USA","Canada","Mexico","MapacheLand");
$countriesAssoc=array("First"=>"USA","Second"=>"Canada","Third"=>"Mexico","Fourth"=>"MapacheLand");

$countriesList=[];
$countriesList[]=['Country'=>"USA",'Population'=>300];
$countriesList[]=['Country'=>"Canada",'Population'=>50];
$countriesList[]=['Country'=>"Mexico",'Population'=>80];

$arrayComplex=array('Name'=>'John'
       
,'Age'=>33
       
,'Address'=>['Name'=>'MapacheLand','City'=>'Racoon City']);

Debug::var_dump(Collection::first($countries));
Debug::var_dump(Collection::first($countriesAssoc));
Debug::var_dump(Collection::firstKey($countriesAssoc));

echo
Collection::generateTable($countriesList);

Debug::var_dump(Collection::arrayKeyLower($arrayComplex));
Debug::var_dump(Collection::arrayKeyUpper($arrayComplex));


Details

Mapache Commons

It's a set of useful functions for PHP. The name is a pun (Mapache in spanish is "raccoon")

Build Status Packagist [Maintenance]() [composer]() [php]() [php]() [CocoaPods]()

Mapache Commons __Mapache Commons__

Goals

It's a set of useful function with the next requirements: * The function mustn't have dependencies (unless it requires a php module). * The function must be FAST and memory friendly over the syntax sugar. * The function must be able to run statically and it must be self contained. * The function must be generic and it must solve generic problems. For example, a function that calculates the VAT of a specific country is not allowed.

Families

  • Collection
  • Text
  • Debug

Collection

It's a class with a collection of functions related with arrays and lists.

splitOpeningClosing

> splitOpeningClosing($text,[$openingTag='('],[$closingTag=')'],[$startPosition=0],[$excludeEmpty=true],[$includeTag=false])

Split a string by an opening and closing tag and returns an array with the result.

> splitOpeningClosing('hello(a,b,c)world(d,e,f)') > returns ['hello','a,b,c','world','d,e,f']

> splitOpeningClosing{'hello{a,b,c}world{d,e,f}','{','}') > returns ['hello','a,b,c','world','d,e,f']

> splitOpeningClosing('hello(a,b(,c)world(d,e,f)') > returns ['hello','a,b(,c','world','d,e,f']

splitNotString

Split a string by ignoring parts of string where values are between " or '.

> splitNotString($text,$separator,[$offset=0],[$excludeEmpty=true])

Collection::splitNotString('a,b,"CC,D,E",e,f' , ",");
// returns ['a' , 'b' , 'CC,D,E' , 'e' , 'f']

arrayChangeKeyCaseRecursive

It changes the case (to lower or upper case) of the keys of an array recursively

> arrayChangeKeyCaseRecursive($arr,$case=CASE_LOWER/CASE_UPPER)

$arr=['A'=>'a','b'=>'b'];
Collection::arrayChangeKeyCaseRecursive($arr);
// returns ['a'=>'a','b'=>'b']
Collection::arrayChangeKeyCaseRecursive($arr,true);
// returns ['A'=>'a','B'=>'b']

arraySearchField

It returns the first (or all) key(s) inside an array/object in an array that matches the value of the field<br>

For example, let's say the next array

[

['name'=>'john'],
['name'=>'mary']

]

And we want to find the first "name" equals to "mary"

$array=[]; // our array with all data
$key=arraySearchField($array,'name','mary');

> arraySearchField($array,$fieldName,$value)

Collection::arraySearchField(
    [['name'=>'john'],['name'=>'mary']],'name','mary');
// returns 1

Collection::arraySearchField(
    [(object)['name'=>'john'],(object)['name'=>'mary']],'name','mary');
// returns 1
Collection::arraySearchField(
    [['name'=>'john'],['name'=>'mary'],['name'=>'mary']],'name','mary',true);
// returns [1,2]
              

isAssoc

> isAssoc($array)

Returns true if array is an associative array, false is it's an indexed array

first

> first($array)

Returns the first element of an array. Sometimes the first element is not the index [0], for example ['key1'=>1,0=2] where the first element is 'key1' and not 0. This function always returns the right value.

firstKey

> firstKey($array)

Returns the first key of an array.

arrayKeyLower

> arrayKeyLower($arr)

Change the case of all the keys to lowercase

arrayKeyUpper

>arrayKeyUpper($arr)

Change the case of all the keys to lowercase

generateTable

>generateTable($array,$css=true)

Generate a html table from an array

Debug

It's a class with a collection of functions related with debug.

var_dump

>var_dump($value,$console=false)

Alternative to var_dump. It "pre" the result or it shows the result in the console of javascript.

>var_dump($value,true) // returns a var_dump visible via the console of javascript (browser)

WriteLog

>WriteLog($logFile,$txt)

It writes a log file and adds the txt to the log. If the log file is full (10mb) then it's emptied.

Text

It's a class with a collection of functions related with strings.

getArgument()

> Text::getArgument($txt,[$set='='],[$trimValue=true])

Returns an array with the name of the argument and value (if any). It always returns a two dimension array

> Example Text::getArgument('alpha=hello') > ['alpha','hello']

> Example Text::getArgument('alpha:hello',':') > ['alpha','hello']

strPosNotSpace()

> Text::strPosNotSpace($txt,[$offset=0])

Returns the first position of a string that it's not a space

Text::strPosNotSpace('   abc  def');
// returns 3

isUpper

> isUpper($str)

Returns true if the str is (completelly) uppercase

isLower

> isLower($str)

Returns true if the str is (completelly) lowercase

stripQuotes

> stripQuotes($text)

Strip quotes of a text (" or ')

Example:

Text::stripQuotes('"hello world"');
// returns hello world

  • If the value is not quoted then it is not touched.
  • If the value is not correctly closed ("hello or "hello' ), then the quota is not removed.
  • The value is trimmed ' "hello world"' --> 'hello world'

between

> between($haystack, $startNeedle, $endNeedle,&$offset=0, $ignoreCase=false)

Returns the text between two needles.

> Text::between('Hello Brave World','Hello','World') // returns " Brave "

replaceBetween

> replaceBetween($haystack, $startNeedle, $endneedle, $replaceText, &$offset=0,$$replaceTag=false)

Replace the text between two needles * If $replaceTag is true then it also replaces the $startNeedle and $endneedle

> Text::replaceBetween('Hello Brave World','Hello','World',' Wayne ') // returns "Hello Wayne World"

removeFirstChars

> removeFirstChars($txt,$length=1)

Remove the first character(s) for a string

> Text::removeFirstChars('Hello') // returns "ello"

removeLastChars

> removeLastChars($txt,$length=1)

Remove the last character(s) for a string

> Text::removeLastChars('Hello') // returns "Hell"

parseArg

It transforms a text = 'a1=1,a2=2' into an associative array. It uses the method parse_str() to do the conversion

> parseArg($text, $separator = ',')

Text::parseArg('a=1,b=1');
// returns ['a'=>'1','b'=>'1']

naturalArg

It parses a natural string and returns a declarative array. A "natural string", it is a set of values or arguments separated by space , where a value is the index and the new one is the value of the index.

> naturalArg($text, $separator = ',')

  • $text the input expression
  • $separator is a associative array where the key is the key of the end result, and the value of each key is * first = first value. This value is the first of the string expression * req = required value. If the value is missing then it returns null * opt = optional value. If the value is missing the the field returns null
Text::naturalArg('select * from table where 1=1'
                ,['select'=>'req','from'=>'req','where'=>'opt']);
// returns ['select'=>'*','from'=>'table','where'=>'1=1']

Text::naturalArg('item export table inport file'
                ,['item'=>'first','export'=>'opt','inport'=>'opt']);
// returns: ['item' => 'item', 'export' => 'table', 'inport' => 'file']

camelCase

Retains the case of the text minus the first letter that it's converted in lowercase.

Example:

Text::camelCase('HelloWorld');
// return "helloWorld";
Text::camelCase('hello_world');
// return "helloWorld";

strposArray

It find the first (or last) ocurrence of a text. Unlikely strpos(), this method allows to find more than one neddle.

> function strposArray($haystack, $needles,$offset=0,$last=false)

Example:

Text::strposArray('a,b.d.e,f.g',['x','t','.']);
// return 3
Text::strposArray('a,b.d.e,f.g',['x','t',','],0,true);
// return 7

removeParenthesis

Remove the initial and final parenthesis but only if both matches. If the $start and $end arguments are arrays then both must have the same count and arrays are compared by pair of index

Example:

Text::removeParenthesis('hello');
// return "hello";
Text::removeParenthesis('(hello)');
// return "hello";
Text::removeParenthesis('[hello]'
    ,['(','{','[']
    ,[')','}',']']);
// returns "hello"
Text::removeParenthesis("'hello'"
    ,"'"
    ,"'");
// returns "hello"

hasParenthesis

Returns true if it has both parenthesis.

Example:

Text::hasParenthesis('hello');
// return false;
Text::hasParenthesis('(hello)');
// return true;

addParenthesis

It adds parenthesis only if the original input does not have it.

Example:

Text::addParenthesis('hello');
// return '(hello)';
Text::addParenthesis('(hello)');
// return '(hello)';

Version list

  • 1.17 New Method Text::str_replace_ex()
  • 1.16 New methods Text::wildcardComparison() and Text::endsWith()
  • 1.15 New method Text::parseArg2()
  • 1.14 Text::camelCase() solved a small bug
  • 1.13 Text::replaceCurlyVariable() updated
  • 1.12 * Collection:splitOpeningClosing added argument $includeTag
  • 1.11 * Text::replaceCurlyVariable Added method
  • 1.10 * Text::strPosNotSpace() added argument $charlist
  • 1.9 2019-12-09 * Text::replacetext() it does not crashes if the end tag is missing. * Text::replacetext() it as a new argument
  • 1.8 2019-12-04 * Text::between() now allows empty $startNeedle and $endNeedle
  • 1.7 2019-12-04 new methods * Text::addParenthesis() * Text::hasParenthesis()
  • 1.6 2019-12-04 new methods * Text::parseArg() * Text::naturalArg() * Text::strposArray() * Text::camelCase() * Text::removeParenthesis() * Collection::arrayChangeKeyCaseRecursive() * Collection::arraySearchField()
  • 1.5 2019-03-10 new functions: Collection:splitOpeningClosing() Text::strPosNotSpace() Text::getArgument() Collection::splitNotString()
  • 1.4 2019-02-16 New functions Text::removeFirstChars(),Text::removeLastChars()
  • 1.3 2019-02-16 Added new methods and Unit test.
  • 1.2 2018-10-27 Some changes in the class collection.
  • 1.0 2018-09-18 First version

License

Apache-2.0.


  Files folder image Files  
File Role Description
Files folder imagedocs (2 files)
Files folder imageexamples (2 files)
Files folder imagelib (3 files)
Files folder imagetest (4 files)
Accessible without login Plain text file .travis.yml Data Auxiliary data
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file LICENSE Lic. License text
Accessible without login Plain text file phpunit.xml Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation

  Files folder image Files  /  docs  
File Role Description
  Accessible without login Image file raccoon.png Data Auxiliary data
  Accessible without login Image file raccoon_small.png Icon Icon image

  Files folder image Files  /  examples  
File Role Description
  Accessible without login Plain text file testCollection.php Example Example script
  Accessible without login Plain text file testDebug.php Example Example script

  Files folder image Files  /  lib  
File Role Description
  Plain text file Collection.php Class Class source
  Plain text file Debug.php Class Class source
  Plain text file Text.php Class Class source

  Files folder image Files  /  test  
File Role Description
  Accessible without login Plain text file bootstrap.php Aux. Auxiliary script
  Plain text file CollectionTest.php Class Class source
  Plain text file DebugTest.php Class Class source
  Plain text file TextTest.php Class Class source

 Version Control Unique User Downloads Download Rankings  
 100%
Total:36
This week:1
All time:10,913
This week:560Up