phpcs and docs

This commit is contained in:
Ade Attwood 2017-09-17 20:50:44 +01:00
parent 074ca1ee4b
commit 5ee2a60fc1
19 changed files with 230 additions and 192 deletions

View file

@ -3,7 +3,13 @@
<description>Yii addon coding standards</description> <description>Yii addon coding standards</description>
<file>./src</file> <file>./src</file>
<file>./tests</file>
<exclude-pattern>*/_output/*</exclude-pattern>
<exclude-pattern>*/_data/*</exclude-pattern>
<exclude-pattern>**.*.css</exclude-pattern>
<exclude-pattern>**.*.js</exclude-pattern>
<arg name="colors"/> <arg name="colors"/>
<rule ref="PSR1"/> <rule ref="PSR1"/>
@ -14,12 +20,26 @@
<rule ref="Squiz.Classes.ValidClassName.NotCamelCaps"> <rule ref="Squiz.Classes.ValidClassName.NotCamelCaps">
<exclude-pattern>*/tests/*</exclude-pattern> <exclude-pattern>*/tests/*</exclude-pattern>
<exclude-pattern>*/migrations/*</exclude-pattern> </rule>
<rule ref="Generic.CodeAnalysis.UnusedFunctionParameter.Found">
<exclude-pattern>*/tests/*</exclude-pattern>
</rule> </rule>
<rule ref="PSR1.Classes.ClassDeclaration.MissingNamespace"> <rule ref="PSR1.Classes.ClassDeclaration.MissingNamespace">
<exclude-pattern>*/tests/*</exclude-pattern> <exclude-pattern>*/tests/*</exclude-pattern>
<exclude-pattern>*/migrations/*</exclude-pattern> </rule>
<rule ref="PEAR.Commenting.FunctionComment.MissingParamTag">
<exclude-pattern>*/tests/*</exclude-pattern>
</rule>
<rule ref="PSR2.Methods.MethodDeclaration.Underscore">
<exclude-pattern>*/tests/*</exclude-pattern>
</rule>
<rule ref="PEAR.Commenting.FunctionComment.Missing">
<exclude-pattern>*/tests/*</exclude-pattern>
</rule> </rule>
<rule ref="Generic.Commenting.Todo.CommentFound"> <rule ref="Generic.Commenting.Todo.CommentFound">
@ -67,6 +87,7 @@
<rule ref="PEAR.Commenting"> <rule ref="PEAR.Commenting">
<exclude name="PEAR.Commenting.FileComment"/> <exclude name="PEAR.Commenting.FileComment"/>
<exclude name="PEAR.Commenting.ClassComment.InvalidPackage"/>
</rule> </rule>
<rule ref="PEAR.Commenting.FileComment.MissingCategoryTag"> <rule ref="PEAR.Commenting.FileComment.MissingCategoryTag">

View file

@ -34,7 +34,7 @@ class ActiveRecordCollection extends \yiiaddon\helpers\ArrayObject
*/ */
public function map($key, $value) public function map($key, $value)
{ {
return new ArrayObject(ArrayHelper::map((array)$this, $key, $value)); return new ArrayObject(ArrayHelper::map((array) $this, $key, $value));
} }
} }

View file

@ -19,7 +19,7 @@ class ActiveQuery extends \yii\db\ActiveQuery
/** /**
* Overrides the Yii method to return an ActiveRecordCollection instead of an array * Overrides the Yii method to return an ActiveRecordCollection instead of an array
* *
* @param mixed $db * @param mixed $db The DB connection used to create the DB command.
* *
* @return ActiveRecordCollection * @return ActiveRecordCollection
*/ */

View file

@ -39,7 +39,7 @@ class ActiveRecord extends \yii\db\ActiveRecord
*/ */
public function parseAttribute($attribute, $defalts = []) public function parseAttribute($attribute, $defalts = [])
{ {
return ArrayHelper::parseAttribute($this, $attribute, $defalts); return ArrayHelper::parseAttribute($this, $attribute, $defalts);
} }
/** /**

View file

@ -35,7 +35,7 @@ trait Rankable
{ {
$query = self::find(); $query = self::find();
if ( $this->rankGoup ) { if ($this->rankGoup) {
$query->where([$this->rankGroup => $this->{$this->rankGroup}]); $query->where([$this->rankGroup => $this->{$this->rankGroup}]);
} }
@ -48,31 +48,31 @@ trait Rankable
$group = $this->rankGoup; $group = $this->rankGoup;
$old_rank = $this->{ $rank_filed }; $old_rank = $this->{ $rank_filed };
if ( $new_rank == $old_rank ) { if ($new_rank == $old_rank) {
return true; return true;
} }
$value = ''; $value = '';
if ( $new_rank > $old_rank ) { if ($new_rank > $old_rank) {
$value = $rank_filed . ' - 1'; $value = $rank_filed.' - 1';
$where = $rank_filed . '>= :rank1 AND ' . $rank_filed . ' <= :rank2'; $where = $rank_filed.'>= :rank1 AND '.$rank_filed.' <= :rank2';
} else { } else {
$value = $rank_filed . ' + 1'; $value = $rank_filed.' + 1';
$where = $rank_filed . ' <= :rank1 AND ' . $rank_filed . ' >= :rank2'; $where = $rank_filed.' <= :rank1 AND '.$rank_filed.' >= :rank2';
} }
if ( $group ) { if ($group) {
$where .= ' AND ' . $group . ' = ' . $this->{ $group }; $where .= ' AND '.$group.' = '.$this->{ $group };
} }
$query = Yii::$app->db->createCommand() $query = Yii::$app->db->createCommand()
->update( self::tableName(), [ $rank_filed => new Expression( $value ) ], $where ) ->update(self::tableName(), [ $rank_filed => new Expression($value) ], $where)
->bindValue( ':rank1', $old_rank ) ->bindValue(':rank1', $old_rank)
->bindValue( ':rank2', $new_rank ) ->bindValue(':rank2', $new_rank)
->execute(); ->execute();
$this->updateAttributes( [ 'rank' => $new_rank ] ); $this->updateAttributes([ 'rank' => $new_rank ]);
return true; return true;
} }

View file

@ -8,7 +8,7 @@ use yii\web\Response;
/** /**
* Minifies the html output of the page * Minifies the html output of the page
* *
* @category PHP * @category PHP
* @package adeattwood\yii-addon * @package adeattwood\yii-addon
* @author Ade Attwood <hello@adeattwood.co.uk> * @author Ade Attwood <hello@adeattwood.co.uk>
@ -61,23 +61,24 @@ class PageMin extends \yii\base\ActionFilter
*/ */
public function minifyHtml( $input ) public function minifyHtml( $input )
{ {
if(trim($input) === "") return $input; if(trim($input) === '') { return $input;
}
$input = preg_replace_callback('#<([^\/\s<>!]+)(?:\s+([^<>]*?)\s*|\s*)(\/?)>#s', function($matches) { $input = preg_replace_callback('#<([^\/\s<>!]+)(?:\s+([^<>]*?)\s*|\s*)(\/?)>#s', function($matches) {
return '<' . $matches[1] . preg_replace('#([^\s=]+)(\=([\'"]?)(.*?)\3)?(\s+|$)#s', ' $1$2', $matches[2]) . $matches[3] . '>'; return '<'.$matches[1].preg_replace('#([^\s=]+)(\=([\'"]?)(.*?)\3)?(\s+|$)#s', ' $1$2', $matches[2]).$matches[3].'>';
}, str_replace("\r", "", $input)); }, str_replace("\r", '', $input));
if(strpos($input, ' style=') !== false) { if(strpos($input, ' style=') !== false) {
$input = preg_replace_callback('#<([^<]+?)\s+style=([\'"])(.*?)\2(?=[\/\s>])#s', function($matches) { $input = preg_replace_callback('#<([^<]+?)\s+style=([\'"])(.*?)\2(?=[\/\s>])#s', function($matches) {
return '<' . $matches[1] . ' style=' . $matches[2] . $this->minifyCss($matches[3]) . $matches[2]; return '<'.$matches[1].' style='.$matches[2].$this->minifyCss($matches[3]).$matches[2];
}, $input); }, $input);
} }
if(strpos($input, '</style>') !== false) { if(strpos($input, '</style>') !== false) {
$input = preg_replace_callback('#<style(.*?)>(.*?)</style>#is', function($matches) { $input = preg_replace_callback('#<style(.*?)>(.*?)</style>#is', function($matches) {
return '<style' . $matches[1] .'>'. $this->minifyCss($matches[2]) . '</style>'; return '<style'.$matches[1].'>'.$this->minifyCss($matches[2]).'</style>';
}, $input); }, $input);
} }
if(strpos($input, '</script>') !== false) { if(strpos($input, '</script>') !== false) {
$input = preg_replace_callback('#<script(.*?)>(.*?)</script>#is', function($matches) { $input = preg_replace_callback('#<script(.*?)>(.*?)</script>#is', function($matches) {
return '<script' . $matches[1] .'>'. $this->minifyJs($matches[2]) . '</script>'; return '<script'.$matches[1].'>'.$this->minifyJs($matches[2]).'</script>';
}, $input); }, $input);
} }
return preg_replace( return preg_replace(
@ -113,7 +114,7 @@ class PageMin extends \yii\base\ActionFilter
* Minifies css strings inside the html * Minifies css strings inside the html
* *
* @param string $input The input html * @param string $input The input html
* *
* @return string The output html * @return string The output html
*/ */
public function minifyCss($input) public function minifyCss($input)
@ -157,7 +158,7 @@ class PageMin extends \yii\base\ActionFilter
* Minifies js strings inside the html * Minifies js strings inside the html
* *
* @param string $input The input html * @param string $input The input html
* *
* @return string The output html * @return string The output html
*/ */
public function minifyJs($input) public function minifyJs($input)

View file

@ -19,6 +19,7 @@ use yiiaddon\helpers\Enum;
*/ */
class ArrayHelper extends \yii\helpers\ArrayHelper class ArrayHelper extends \yii\helpers\ArrayHelper
{ {
/** /**
* Creates a array of numbers * Creates a array of numbers
* *
@ -43,8 +44,8 @@ class ArrayHelper extends \yii\helpers\ArrayHelper
public static function numberArray( $max, $min = 0, $step = 1 ) public static function numberArray( $max, $min = 0, $step = 1 )
{ {
$array = []; $array = [];
for( $i = $min; $i <= $max; $i += $step ) { for($i = $min; $i <= $max; $i += $step) {
$array[ $i ] = $i; $array[$i] = $i;
} }
return $array; return $array;
} }
@ -66,22 +67,22 @@ class ArrayHelper extends \yii\helpers\ArrayHelper
*/ */
public static function parseAttribute( $model, $attribute, $defalts = [] ) public static function parseAttribute( $model, $attribute, $defalts = [] )
{ {
if ( !preg_match( '/^([^:]+)(:(\w*))?(:(.*))?$/', $attribute, $matches ) ) { if (!preg_match('/^([^:]+)(:(\w*))?(:(.*))?$/', $attribute, $matches)) {
throw new InvalidConfigException( 'The column must be specified in the format of "attribute", "attribute:format" or "attribute:format:label"' ); throw new InvalidConfigException('The column must be specified in the format of "attribute", "attribute:format" or "attribute:format:label"');
} }
$rawValue = self::getValue( $model, $matches[ 1 ] ); $rawValue = self::getValue($model, $matches[1]);
$format = isset( $matches[ 3 ] ) ? $matches[ 3 ] : self::remove($defalts, 'format', 'text'); $format = isset($matches[3]) ? $matches[3] : self::remove($defalts, 'format', 'text');
$value = Enum::isEmpty( $rawValue ) ? self::remove($defalts, 'value', '( NOT SET )') : Yii::$app->formatter->format( $rawValue, $format ); $value = Enum::isEmpty($rawValue) ? self::remove($defalts, 'value', '( NOT SET )') : Yii::$app->formatter->format($rawValue, $format);
$lable = isset( $matches[ 5 ] ) ? $matches[ 5 ] : $model->getAttributeLabel( $matches[ 1 ] ); $lable = isset($matches[5]) ? $matches[5] : $model->getAttributeLabel($matches[1]);
return new ArrayObject( [ return new ArrayObject([
'format' => $format, 'format' => $format,
'value' => $value, 'value' => $value,
'lable' => $lable, 'lable' => $lable,
'raw' => $rawValue 'raw' => $rawValue
] ); ]);
} }
} }

View file

@ -30,24 +30,24 @@ class ArrayObject extends \ArrayObject
*/ */
public function __construct( $array = [], $flags = null, $iterator_class = 'ArrayIterator' ) public function __construct( $array = [], $flags = null, $iterator_class = 'ArrayIterator' )
{ {
if( $flags === null ) { if($flags === null) {
$flags = self::ARRAY_AS_PROPS; $flags = self::ARRAY_AS_PROPS;
} }
parent::__construct( $array, $flags, $iterator_class ); parent::__construct($array, $flags, $iterator_class);
} }
/** /**
* Test that the ArrayObject contains an item * Test that the ArrayObject contains an item
* *
* @param $item The item to test * @param mixed $item The item to test
* *
* @return bool * @return bool
*/ */
public function contains( $item ) public function contains( $item )
{ {
$flipped = array_flip( ( array )$this ); $flipped = array_flip(( array ) $this);
return isset( $flipped[ $item ] ); return isset($flipped[$item]);
} }
/** /**
@ -59,12 +59,12 @@ class ArrayObject extends \ArrayObject
*/ */
public function randomValue( $count = 1 ) public function randomValue( $count = 1 )
{ {
$arr = ( array )$this; $arr = ( array ) $this;
shuffle( $arr ); shuffle($arr);
$r = array(); $r = array();
for ( $i = 0; $i < $count; $i++ ) { for ($i = 0; $i < $count; $i++) {
$r[] = $arr[$i]; $r[] = $arr[$i];
} }
return $count == 1 ? $r[0] : new self($r); return $count == 1 ? $r[0] : new self($r);
@ -74,7 +74,7 @@ class ArrayObject extends \ArrayObject
* Adds an item to the start of the object * Adds an item to the start of the object
* *
* @param mixed $value The item to prepend * @param mixed $value The item to prepend
* *
* @return void * @return void
*/ */
public function prepend($value) public function prepend($value)
@ -82,7 +82,7 @@ class ArrayObject extends \ArrayObject
$array = $this->getArrayCopy(); $array = $this->getArrayCopy();
if (is_string($value)) { if (is_string($value)) {
$value = (array)$value; $value = (array) $value;
} }
if (is_object($value)) { if (is_object($value)) {
@ -100,7 +100,7 @@ class ArrayObject extends \ArrayObject
*/ */
public function combine($array) public function combine($array)
{ {
$this->exchangeArray(array_merge((array)$this->getArrayCopy(), $array)); $this->exchangeArray(array_merge((array) $this->getArrayCopy(), $array));
} }
/** /**
@ -142,8 +142,8 @@ class ArrayObject extends \ArrayObject
*/ */
public function chunks($count) public function chunks($count)
{ {
$out = []; $out = [];
$array = array_chunk((array)$this, $count); $array = array_chunk((array) $this, $count);
foreach ($array as $chunk) { foreach ($array as $chunk) {
$out[] = new self($chunk); $out[] = new self($chunk);
@ -159,7 +159,7 @@ class ArrayObject extends \ArrayObject
*/ */
public function toJson() public function toJson()
{ {
return \yii\helpers\Json::encode((array)$this); return \yii\helpers\Json::encode((array) $this);
} }
/** /**
@ -177,65 +177,64 @@ class ArrayObject extends \ArrayObject
*/ */
public function toTable( $transpose = false, $recursive = false, $typeHint = true, $tableOptions = [ 'class' => 'table table-bordered table-striped' ], $keyOptions = [], $valueOptions = [ 'style' => 'cursor: default; border-bottom: 1px #aaa dashed;' ], $null = '<span class="not-set">(not set)</span>' ) public function toTable( $transpose = false, $recursive = false, $typeHint = true, $tableOptions = [ 'class' => 'table table-bordered table-striped' ], $keyOptions = [], $valueOptions = [ 'style' => 'cursor: default; border-bottom: 1px #aaa dashed;' ], $null = '<span class="not-set">(not set)</span>' )
{ {
if ( empty( ( array )$this ) ) { if (empty(( array ) $this)) {
return false; return false;
} }
$array = ( array )$this; $array = ( array ) $this;
// Start the table // Start the table
$table = Html::beginTag( 'table', $tableOptions ) . "\n"; $table = Html::beginTag('table', $tableOptions)."\n";
// The header // The header
$table .= "\t<tr>"; $table .= "\t<tr>";
if ( $transpose ) { if ($transpose) {
foreach ( $this as $key => $value ) { foreach ($this as $key => $value) {
if ( $typeHint ) { if ($typeHint) {
$valueOptions['title'] = Enum::getType( strtoupper( $value ) ); $valueOptions['title'] = Enum::getType(strtoupper($value));
} }
if ( is_array( $value ) ) { if (is_array($value)) {
$value = '<pre>' . print_r( $value, true ) . '</pre>'; $value = '<pre>'.print_r($value, true).'</pre>';
} else { } else {
$value = Html::tag( 'span', $value, $valueOptions ); $value = Html::tag('span', $value, $valueOptions);
} }
$table .= "\t\t<th>" . Html::tag( 'span', $key, $keyOptions ) . "</th>" . $table .= "\t\t<th>".Html::tag('span', $key, $keyOptions).'</th>'.'<td>'.$value."</td>\n\t</tr>\n";
"<td>" . $value . "</td>\n\t</tr>\n";
} }
$table .= "</table>"; $table .= '</table>';
return $table; return $table;
} }
if ( !isset( $array[0] ) || !is_array( $array[0] ) ) { if (!isset($array[0]) || !is_array($array[0])) {
$array = array( $array ); $array = array( $array );
} }
// Take the keys from the first row as the headings // Take the keys from the first row as the headings
foreach ( array_keys( $array[0] ) as $heading ) { foreach (array_keys($array[0]) as $heading) {
$table .= '<th>' . Html::tag( 'span', $heading, $keyOptions ) . '</th>'; $table .= '<th>'.Html::tag('span', $heading, $keyOptions).'</th>';
} }
$table .= "</tr>\n"; $table .= "</tr>\n";
// The body // The body
foreach ( $array as $row ) { foreach ($array as $row) {
$table .= "\t<tr>"; $table .= "\t<tr>";
foreach ( $row as $cell ) { foreach ($row as $cell) {
$table .= '<td>'; $table .= '<td>';
// Cast objects // Cast objects
if ( is_object( $cell ) ) { if (is_object($cell)) {
$cell = (array)$cell; $cell = (array) $cell;
} }
if ( $recursive === true && is_array( $cell ) && !empty( $cell ) ) { if ($recursive === true && is_array($cell) && !empty($cell)) {
// Recursive mode // Recursive mode
$table .= "\n" . static::array2table( $cell, true, true ) . "\n"; $table .= "\n".static::array2table($cell, true, true)."\n";
} else { } else {
if ( !is_null( $cell ) && is_bool( $cell ) ) { if ($cell !== null && is_bool($cell)) {
$val = $cell ? 'true' : 'false'; $val = $cell ? 'true' : 'false';
$type = 'boolean'; $type = 'boolean';
} else { } else {
$chk = ( strlen( $cell ) > 0 ); $chk = ( strlen($cell) > 0 );
$type = $chk ? Enum::getType( $cell ) : 'null'; $type = $chk ? Enum::getType($cell) : 'null';
$val = $chk ? htmlspecialchars( (string)$cell ) : $null; $val = $chk ? htmlspecialchars((string) $cell) : $null;
} }
if ( $typeHint ) { if ($typeHint) {
$valueOptions['title'] = $type; $valueOptions['title'] = $type;
} }
$table .= Html::tag( 'span', $val, $valueOptions ); $table .= Html::tag('span', $val, $valueOptions);
} }
$table .= '</td>'; $table .= '</td>';
} }
@ -244,4 +243,5 @@ class ArrayObject extends \ArrayObject
$table .= '</table>'; $table .= '</table>';
return $table; return $table;
} }
} }

View file

@ -38,22 +38,22 @@ class Dumper
); );
public static function dump( $var ) { public static function dump( $var ) {
VarDumper::setHandler( function ( $var ) { VarDumper::setHandler(function ( $var ) {
$cloner = new VarCloner(); $cloner = new VarCloner();
$dumper = 'cli' === PHP_SAPI ? new CliDumper() : new HtmlDumper(); $dumper = 'cli' === PHP_SAPI ? new CliDumper() : new HtmlDumper();
$dumper->setStyles( self::$styles ); $dumper->setStyles(self::$styles);
$dumper->setDisplayOptions( self::$displayOptions ); $dumper->setDisplayOptions(self::$displayOptions);
$dumper->dump( $cloner->cloneVar( $var ) ); $dumper->dump($cloner->cloneVar($var));
} ); });
dump( $var ); dump($var);
} }
public static function dDump( $var ) public static function dDump( $var )
{ {
self::dump( $var ); self::dump($var);
die; die;
} }
@ -61,89 +61,90 @@ class Dumper
{ {
$dataArray = []; $dataArray = [];
$class = new \ReflectionClass( $var ); $class = new \ReflectionClass($var);
$dataArray[ 'name' ] = $class->name; $dataArray['name'] = $class->name;
$methods = $class->getMethods(); $methods = $class->getMethods();
$dataArray[ 'constants'] = ( array )$class->getConstants(); $dataArray['constants'] = ( array ) $class->getConstants();
foreach ( $class->getProperties() as $propertie ) { foreach ($class->getProperties() as $propertie) {
$prop = ''; $prop = '';
if ( $propertie->isPublic() ) { if ($propertie->isPublic()) {
$prop .= "public"; $prop .= 'public';
} elseif ( $propertie->isPrivate() ) { } elseif ($propertie->isPrivate()) {
$prop .= "private"; $prop .= 'private';
} elseif ( $propertie->isProtected() ) { } elseif ($propertie->isProtected()) {
$prop .= "protected"; $prop .= 'protected';
} }
if ( $propertie->isStatic() ) { if ($propertie->isStatic()) {
$prop .= " static"; $prop .= ' static';
} }
$prop .= " \${$propertie->name}"; $prop .= " \${$propertie->name}";
$dataArray[ 'properties' ][] = $prop; $dataArray['properties'][] = $prop;
} }
foreach ( $methods as $method ) { foreach ($methods as $method) {
$prop = ''; $prop = '';
if ( $method->isPublic() ) { if ($method->isPublic()) {
$prop .= "public"; $prop .= 'public';
} elseif ( $method->isPrivate() ) { } elseif ($method->isPrivate()) {
$prop .= "private"; $prop .= 'private';
} elseif ( $method->isProtected() ) { } elseif ($method->isProtected()) {
$prop .= "protected"; $prop .= 'protected';
} }
$prop .= " {$method->name}( "; $prop .= " {$method->name}( ";
$params = ""; $params = '';
foreach ( $method->getParameters() as $parameter ) { foreach ($method->getParameters() as $parameter) {
$params .= "\${$parameter->name}"; $params .= "\${$parameter->name}";
if ( $parameter->isDefaultValueAvailable() ) { if ($parameter->isDefaultValueAvailable()) {
$value = $parameter->getDefaultValue(); $value = $parameter->getDefaultValue();
if ( is_array( $value ) ) { if (is_array($value)) {
$value = "[]"; $value = '[]';
} elseif ( is_bool( $value ) ) { } elseif (is_bool($value)) {
$value = $value ? "true" : "false"; $value = $value ? 'true' : 'false';
} }
$params .= "= {$value}"; $params .= "= {$value}";
// self::dDump( $parameter->getDefaultValue() ); // self::dDump( $parameter->getDefaultValue() );
} }
$params .= ", "; $params .= ', ';
} }
$params = rtrim( $params, ", " ); $params = rtrim($params, ', ');
$prop .= "{$params} )"; $prop .= "{$params} )";
// $prop .= " : {$method->getReturnType()}"; // $prop .= " : {$method->getReturnType()}";
$dataArray[ 'methords' ][ $prop ] = [ $dataArray['methords'][$prop] = [
"file" => $method->getFileName(), 'file' => $method->getFileName(),
"line" => $method->getStartLine(), 'line' => $method->getStartLine(),
'fileLine' => "{$method->getFileName()}:{$method->getStartLine()}", 'fileLine' => "{$method->getFileName()}:{$method->getStartLine()}",
"doc" => $method->getDocComment() 'doc' => $method->getDocComment()
]; ];
} }
sort( $dataArray[ 'properties' ] ); sort($dataArray['properties']);
ksort( $dataArray[ 'constants' ] ); ksort($dataArray['constants']);
ksort( $dataArray[ 'methords' ] ); ksort($dataArray['methords']);
self::dDump( $dataArray ); self::dDump($dataArray);
} }
public static function dDumpInfo( $var ) public static function dDumpInfo( $var )
{ {
self::dumpInfo( $var ); self::dumpInfo($var);
die; die;
} }
} }

View file

@ -48,34 +48,34 @@ class Enum extends \yii\base\Object
*/ */
public static function getType( $var ) public static function getType( $var )
{ {
if (is_null($var)) { if ($var === null) {
return self::TYPE_NULL; return self::TYPE_NULL;
} }
if (is_array( $var )) { if (is_array($var)) {
return self::TYPE_ARRAY; return self::TYPE_ARRAY;
} }
if (is_bool( $var )) { if (is_bool($var)) {
return self::TYPE_BOOL; return self::TYPE_BOOL;
} }
if (is_float( $var ) if (is_float($var)
|| (!is_object($var) && || (!is_object($var) &&
is_numeric( str_replace( ',', '', $var ) ) && strpos( $var, '.' ) > 0 && is_float( ( float )str_replace( ',', '', $var ) )) is_numeric(str_replace(',', '', $var)) && strpos($var, '.') > 0 && is_float(( float ) str_replace(',', '', $var)))
) { ) {
return self::TYPE_FLOAT; return self::TYPE_FLOAT;
} }
if (is_int( $var ) || ( is_numeric( $var ) && is_int( ( int )$var ) )) { if (is_int($var) || ( is_numeric($var) && is_int(( int ) $var) )) {
return self::TYPE_INT; return self::TYPE_INT;
} }
if (is_scalar( $var ) && strtotime( $var ) !== false) { if (is_scalar($var) && strtotime($var) !== false) {
return self::TYPE_DATETIME; return self::TYPE_DATETIME;
} }
if (is_scalar( $var )) { if (is_scalar($var)) {
return self::TYPE_STRING; return self::TYPE_STRING;
} }
@ -99,7 +99,7 @@ class Enum extends \yii\base\Object
*/ */
public static function isEmpty( $var ) public static function isEmpty( $var )
{ {
return !isset( $var ) ? true : ( is_array( $var ) ? empty( $var ) : ( $var === null || $var === '' ) ); return !isset($var) ? true : ( is_array($var) ? empty($var) : ( $var === null || $var === '' ) );
} }
/** /**
@ -120,11 +120,12 @@ class Enum extends \yii\base\Object
*/ */
public static function formatBytes( $bytes, $precision = 2 ) public static function formatBytes( $bytes, $precision = 2 )
{ {
$units = [ 'B', 'KB', 'MB', 'GB', 'TB' ]; $units = [ 'B', 'KB', 'MB', 'GB', 'TB' ];
$bytes = max( $bytes, 0 ); $bytes = max($bytes, 0);
$pow = floor( ( $bytes ? log( $bytes ) : 0 ) / log( 1024 ) ); $pow = floor(( $bytes ? log($bytes) : 0 ) / log(1024));
$pow = min( $pow, count( $units ) - 1 ); $pow = min($pow, count($units) - 1);
$bytes /= pow( 1024, $pow ); $bytes /= pow(1024, $pow);
return round( $bytes, $precision ) . ' ' . $units[$pow]; return round($bytes, $precision).' '.$units[$pow];
} }
} }

View file

@ -31,7 +31,7 @@ use yii\helpers\Url;
*/ */
class RedirectRule extends \yii\web\UrlRule class RedirectRule extends \yii\web\UrlRule
{ {
public $permanents = []; public $permanents = [];
public $temporaries = []; public $temporaries = [];
@ -55,14 +55,13 @@ class RedirectRule extends \yii\web\UrlRule
if(in_array($pathInfo, $this->permanents)) { if(in_array($pathInfo, $this->permanents)) {
$request->setPathInfo($this->name); $request->setPathInfo($this->name);
Yii::$app->response->redirect($this->name, 301); Yii::$app->response->redirect($this->name, 301);
} else if(in_array($pathInfo, $this->temporaries)) { } elseif(in_array($pathInfo, $this->temporaries)) {
$request->setPathInfo($this->name); $request->setPathInfo($this->name);
Yii::$app->response->redirect($this->name, 302); Yii::$app->response->redirect($this->name, 302);
} }
parent::parseRequest($manager, $request); parent::parseRequest($manager, $request);
Yii::$app->end(); Yii::$app->end();
} }
} }

View file

@ -202,7 +202,7 @@ class View extends \yii\web\View
$this->registerGoogleAnalytics(); $this->registerGoogleAnalytics();
} }
return '<title>' . $this->title . '</title>' . parent::renderHeadHtml(); return '<title>'.$this->title.'</title>'.parent::renderHeadHtml();
} }
/** /**
@ -212,7 +212,7 @@ class View extends \yii\web\View
*/ */
public function registerGoogleAnalytics() public function registerGoogleAnalytics()
{ {
$js = "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','$this->googleAnalyticsFile','$this->googleAnalyticsVar');"; $js = "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','$this->googleAnalyticsFile','$this->googleAnalyticsVar');";
$js .= "$this->googleAnalyticsVar('create', '$this->googleAnalyticsCode', 'auto');"; $js .= "$this->googleAnalyticsVar('create', '$this->googleAnalyticsCode', 'auto');";
$js .= "$this->googleAnalyticsVar('send', 'pageview');"; $js .= "$this->googleAnalyticsVar('send', 'pageview');";

View file

@ -12,7 +12,8 @@ namespace yiiaddon\tests\_data;
* @since v0.1 * @since v0.1
*/ */
class ModelOne extends \yii\base\Model class ModelOne extends \yii\base\Model
{ {
/** /**
* The first test proprety * The first test proprety
* *
@ -31,4 +32,5 @@ class ModelOne extends \yii\base\Model
[ [ 'propOne' ], 'string' ] [ [ 'propOne' ], 'string' ]
]; ];
} }
} }

View file

@ -15,6 +15,11 @@ use yiiaddon\tests\_data\ActiveModel;
class ActiveRecordCest class ActiveRecordCest
{ {
/**
* The instace of ActiveModel that we will be using in the tests
*
* @var ActiveModel
*/
public $model; public $model;
public function _before( UnitTester $I ) public function _before( UnitTester $I )

View file

@ -16,6 +16,11 @@ use yiiaddon\tests\_data\ActiveModel;
class ActiveRecordCollectionCest class ActiveRecordCollectionCest
{ {
/**
* The model collection built before every test
*
* @var ActiveRecordCollection
*/
public $model; public $model;
public function _before( UnitTester $I ) public function _before( UnitTester $I )

View file

@ -15,8 +15,6 @@ use yiiaddon\tests\_data\ModelOne;
class ArrayHelperCest class ArrayHelperCest
{ {
public function _before( UnitTester $I ) public function _before( UnitTester $I )
{ {
} }
@ -27,49 +25,50 @@ class ArrayHelperCest
public function testNumberArray( UnitTester $I ) public function testNumberArray( UnitTester $I )
{ {
$array = ArrayHelper::numberArray( 10, 2, 2 ); $array = ArrayHelper::numberArray(10, 2, 2);
$I->assertEquals( $array[ 2 ], 2 ); $I->assertEquals($array[2], 2);
$I->assertFalse( isset( $array[ 3 ] ) ); $I->assertFalse(isset($array[3]));
$I->assertEquals( $array[ 4 ], 4 ); $I->assertEquals($array[4], 4);
} }
public function testNumberArrayWithStep( UnitTester $I ) public function testNumberArrayWithStep( UnitTester $I )
{ {
$array = ArrayHelper::numberArray( 10 ); $array = ArrayHelper::numberArray(10);
$I->assertEquals( $array[ 0 ], 0 ); $I->assertEquals($array[0], 0);
$I->assertEquals( $array[ 10 ], 10 ); $I->assertEquals($array[10], 10);
$I->assertFalse( isset( $array[ 11 ] ) ); $I->assertFalse(isset($array[11]));
} }
public function testParseAttribute( UnitTester $I ) public function testParseAttribute( UnitTester $I )
{ {
$model = new ModelOne; $model = new ModelOne;
$model->propOne = "test"; $model->propOne = 'test';
$data = ArrayHelper::parseAttribute( $model, 'propOne' ); $data = ArrayHelper::parseAttribute($model, 'propOne');
$I->assertEquals( $data->format, 'text' ); $I->assertEquals($data->format, 'text');
$I->assertEquals( $data->lable, 'Prop One' ); $I->assertEquals($data->lable, 'Prop One');
$I->assertEquals( $data->value, 'test' ); $I->assertEquals($data->value, 'test');
$I->assertEquals( $data->raw, 'test' ); $I->assertEquals($data->raw, 'test');
} }
public function testErrorWithParseAttribute( UnitTester $I ) public function testErrorWithParseAttribute( UnitTester $I )
{ {
$model = new ModelOne; $model = new ModelOne;
$model->propOne = "test"; $model->propOne = 'test';
try { try {
$data = ArrayHelper::parseAttribute( $model, 'not_a_prop' ); $data = ArrayHelper::parseAttribute($model, 'not_a_prop');
$I->fail( 'Not exseption thrown' ); $I->fail('Not exseption thrown');
} catch ( \yii\base\UnknownPropertyException $e ) { } catch (\yii\base\UnknownPropertyException $e) {
} catch ( \Exception $e ) { $I->assertEquals($e->getMessage(), 'Getting unknown property: yiiaddon\tests\_data\ModelOne::not_a_prop');
$I->fail( '\yii\base\UnknownPropertyException should have been thorwn' ); } catch (\Exception $e) {
$I->fail('\yii\base\UnknownPropertyException should have been thorwn');
} }
} }
@ -77,13 +76,15 @@ class ArrayHelperCest
{ {
$model = new ModelOne; $model = new ModelOne;
$model->propOne = "test"; $model->propOne = 'test';
try { try {
$data = ArrayHelper::parseAttribute( $model, '' ); $data = ArrayHelper::parseAttribute($model, '');
$I->fail( 'Not exseption thrown' ); $I->fail('Not exseption thrown');
} catch ( \yii\base\InvalidConfigException $e ) { } catch (\yii\base\InvalidConfigException $e) {
} catch ( \Exception $e ) { $I->assertEquals($e->getMessage(), 'The column must be specified in the format of "attribute", "attribute:format" or "attribute:format:label"');
$I->fail( '\yii\base\InvalidConfigException should have been thorwn' ); } catch (\Exception $e) {
$I->fail('\yii\base\InvalidConfigException should have been thorwn');
} }
} }
} }

View file

@ -22,7 +22,7 @@ class ArrayObjectCest
public function _before( UnitTester $I ) public function _before( UnitTester $I )
{ {
$this->arrayObject = new ArrayObject( $this->array ); $this->arrayObject = new ArrayObject($this->array);
} }
public function _after( UnitTester $I ) public function _after( UnitTester $I )
@ -31,7 +31,7 @@ class ArrayObjectCest
public function testArrayAsProps( UnitTester $I ) public function testArrayAsProps( UnitTester $I )
{ {
$I->assertEquals( $this->arrayObject->key_one, "Value One" ); $I->assertEquals($this->arrayObject->key_one, 'Value One');
} }
/** /**
@ -41,8 +41,8 @@ class ArrayObjectCest
*/ */
public function testArrayContains( UnitTester $I ) public function testArrayContains( UnitTester $I )
{ {
$I->assertTrue( $this->arrayObject->contains( "Value One" ) ); $I->assertTrue($this->arrayObject->contains('Value One'));
$I->assertFalse( $this->arrayObject->contains( "Not in array" ) ); $I->assertFalse($this->arrayObject->contains('Not in array'));
} }
/** /**
@ -54,14 +54,14 @@ class ArrayObjectCest
{ {
$table = $this->arrayObject->toTable(); $table = $this->arrayObject->toTable();
$I->assertContains( '<table class="table table-bordered table-striped">', $table ); $I->assertContains('<table class="table table-bordered table-striped">', $table);
$I->assertContains( '<span title="string" style="cursor: default; border-bottom: 1px #aaa dashed;">Value One</span>', $table ); $I->assertContains('<span title="string" style="cursor: default; border-bottom: 1px #aaa dashed;">Value One</span>', $table);
} }
public function testRandomValue( UnitTester $I ) public function testRandomValue( UnitTester $I )
{ {
for( $i = 0; $i < 5; $i++ ) { for($i = 0; $i < 5; $i++) {
$I->assertContains( $this->arrayObject->randomValue(), $this->array ); $I->assertContains($this->arrayObject->randomValue(), $this->array);
} }
} }

View file

@ -24,8 +24,8 @@ class EnumCest
public function testNumberArray( UnitTester $I ) public function testNumberArray( UnitTester $I )
{ {
$I->assertEquals( Enum::formatBytes( 28434322.25 ), '27.12 MB' ); $I->assertEquals(Enum::formatBytes(28434322.25), '27.12 MB');
$I->assertEquals( Enum::formatBytes( 17328347842.25, 3 ), '16.138 GB' ); $I->assertEquals(Enum::formatBytes(17328347842.25, 3), '16.138 GB');
} }
/** /**
@ -44,8 +44,9 @@ class EnumCest
'unknown' => new StdClass() 'unknown' => new StdClass()
]; ];
foreach ( $array as $type => $var ) { foreach ($array as $type => $var) {
$I->assertEquals( $type, Enum::getType( $var ) ); $I->assertEquals($type, Enum::getType($var));
} }
} }
} }

View file

@ -10,12 +10,12 @@
* @since v0.1 * @since v0.1
*/ */
require __DIR__ . "/../../vendor/autoload.php"; require __DIR__.'/../../vendor/autoload.php';
require __DIR__ . "/../../vendor/yiisoft/yii2/Yii.php"; require __DIR__.'/../../vendor/yiisoft/yii2/Yii.php';
$config = [ $config = [
'id' => 'Yii Helpers Tests', 'id' => 'Yii Helpers Tests',
'basePath' => dirname( __DIR__ ) 'basePath' => dirname(__DIR__)
]; ];
( new yii\web\Application( $config ) ); ( new yii\web\Application($config) );