Skip to content

Commit

Permalink
Refactoring to put helpers in a class
Browse files Browse the repository at this point in the history
  • Loading branch information
specialtactics committed Jul 21, 2019
1 parent 8ae1e09 commit f4f1964
Show file tree
Hide file tree
Showing 7 changed files with 126 additions and 76 deletions.
75 changes: 9 additions & 66 deletions helpers/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,100 +13,43 @@ function APIUser()
/**
* Recursively camel-case an array's keys
*
* @deprecated Use Helpers.php
* @param $array
* @param int|null $levels How many levels of an array keys to transform - by default recurse infiniately (null)
* @param int|null $levels How many levels of an array keys to transform - by default recurse infinitely (null)
* @return array $array
*/
function camel_case_array_keys($array, $levels = null)
{
foreach (array_keys($array) as $key) {
// Get a reference to the value of the key (avoid copy)
// Then remove that array element
$value = &$array[$key];
unset($array[$key]);

// Transform key
$transformedKey = camel_case($key);

// Recurse
if (is_array($value) && (is_null($levels) || --$levels > 0)) {
$value = camel_case_array_keys($value, $levels);
}

// Store the transformed key with the referenced value
$array[$transformedKey] = $value;

// We'll be dealing with some large values, so memory cleanup is important
unset($value);
}

return $array;
return Specialtactics\L5Api\Helpers::camelCaseArrayKeys($array, $levels);
}
}

if (! function_exists('snake_case_array_keys')) {
/**
* Recursively snake-case an array's keys
*
* @deprecated Use Helpers.php
* @param $array
* @param int|null $levels How many levels of an array keys to transform - by default recurse infiniately (null)
* @param int|null $levels How many levels of an array keys to transform - by default recurse infinitely (null)
* @return array $array
*/
function snake_case_array_keys(array $array, $levels = null)
{
foreach (array_keys($array) as $key) {
// Get a reference to the value of the key (avoid copy)
// Then remove that array element
$value = &$array[$key];
unset($array[$key]);

// Transform key
$transformedKey = snake_case($key);

// Recurse
if (is_array($value) && (is_null($levels) || --$levels > 0)) {
$value = snake_case_array_keys($value, $levels);
}

// Store the transformed key with the referenced value
$array[$transformedKey] = $value;

// We'll be dealing with some large values, so memory cleanup is important
unset($value);
}

return $array;
}
}

if (! function_exists('get_calling_method')) {
/**
* Get the calling method name
*
* @return string
*/
function get_calling_method()
{
return debug_backtrace()[1]['function'];
return Specialtactics\L5Api\Helpers::snakeCaseArrayKeys($array, $levels);
}
}

if (! function_exists('model_relation_name')) {
/**
* Converts the name of a model class to the name of the relation of this resource on another model
*
* @deprecated Use Helpers.php
* @param string $resourceName The name of the resource we are dealing with
* @param string $relationType The type of relation - ie.. one to.. X ('one', 'many')
* @return string The name of the relation, as it would appear inside an eloquent model
* @throws \Exception
*/
function model_relation_name($resourceName, $relationType = 'many')
{
if ($relationType == 'many') {
return lcfirst(str_plural(class_basename($resourceName)));
} elseif ($relationType == 'one') {
return lcfirst(class_basename($resourceName));
} else {
throw new \Exception('Undefined relation type');
}
return Specialtactics\L5Api\Helpers::modelRelationName($resourceName, $relationType);
}
}
5 changes: 3 additions & 2 deletions src/APIBoilerplate.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Config;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Illuminate\Support\Str;
use Specialtactics\L5Api\Helpers;

class APIBoilerplate
{
Expand Down Expand Up @@ -95,9 +96,9 @@ public static function formatKeyCaseAccordingToResponseFormat($input, $levels =
$caseFormat = static::getResponseCaseType();

if ($caseFormat == static::CAMEL_CASE) {
$transformed = camel_case_array_keys($input, $levels);
$transformed = Helpers::camelCaseArrayKeys($input, $levels);
} elseif ($caseFormat == static::SNAKE_CASE) {
$transformed = snake_case_array_keys($input, $levels);
$transformed = Helpers::snakeCaseArrayKeys($input, $levels);
} else {
// Shouldn't happen
$transformed = $input;
Expand Down
7 changes: 4 additions & 3 deletions src/Exceptions/RestfulApiExceptionHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Exception;
use Dingo\Api\Exception\Handler as ExceptionHandler;
use Specialtactics\L5Api\APIBoilerplate;
use Specialtactics\L5Api\Helpers;

/**
* This class extends the Dingo API Exception Handler, and can be used to modify it's functionality, if required
Expand Down Expand Up @@ -47,7 +48,7 @@ protected function prepareReplacements(Exception $exception)
// Format response object keys
$updatedFormat = [];
foreach ($this->format as $key => $value) {
$updatedFormat[APIBoilerplate::formatKeyCaseAccordingToReponseFormat($key)] = $value;
$updatedFormat[APIBoilerplate::formatCaseAccordingToResponseFormat($key)] = $value;
}
$this->format = $updatedFormat;

Expand Down Expand Up @@ -77,9 +78,9 @@ protected function formatCaseOfValidationMessages($replacements)
$errorMessages = $replacements[$errorKey];

if (Config(APIBoilerplate::CASE_TYPE_CONFIG_PATH, APIBoilerplate::DEFAULT_CASE) == APIBoilerplate::CAMEL_CASE) {
$errorMessages = camel_case_array_keys($errorMessages);
$errorMessages = Helpers::camelCaseArrayKeys($errorMessages);
} else {
$errorMessages = snake_case_array_keys($errorMessages);
$errorMessages = Helpers::snakeCaseArrayKeys($errorMessages);
}

$replacements[$errorKey] = $errorMessages;
Expand Down
102 changes: 102 additions & 0 deletions src/Helpers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
<?php

namespace Specialtactics\L5Api;

use Illuminate\Support\Str;

class Helpers
{
/**
* Recursively camel-case an array's keys
*
* @param $array
* @param int|null $levels How many levels of an array keys to transform - by default recurse infinitely (null)
* @return array $array
*/
public static function camelCaseArrayKeys($array, $levels = null)
{
foreach (array_keys($array) as $key) {
// Get a reference to the value of the key (avoid copy)
// Then remove that array element
$value = &$array[$key];
unset($array[$key]);

// Transform key
$transformedKey = Str::camel($key);

// Recurse
if (is_array($value) && (is_null($levels) || --$levels > 0)) {
$value = static::camelCaseArrayKeys($value, $levels);
}

// Store the transformed key with the referenced value
$array[$transformedKey] = $value;

// We'll be dealing with some large values, so memory cleanup is important
unset($value);
}

return $array;
}

/**
* Recursively snake-case an array's keys
*
* @param $array
* @param int|null $levels How many levels of an array keys to transform - by default recurse infinitely (null)
* @return array $array
*/
public static function snakeCaseArrayKeys(array $array, $levels = null)
{
foreach (array_keys($array) as $key) {
// Get a reference to the value of the key (avoid copy)
// Then remove that array element
$value = &$array[$key];
unset($array[$key]);

// Transform key
$transformedKey = Str::snake($key);

// Recurse
if (is_array($value) && (is_null($levels) || --$levels > 0)) {
$value = static::snakeCaseArrayKeys($value, $levels);
}

// Store the transformed key with the referenced value
$array[$transformedKey] = $value;

// We'll be dealing with some large values, so memory cleanup is important
unset($value);
}

return $array;
}

/**
* Get the calling method name
*
* @return string
*/
public static function getCallingMethod()
{
return debug_backtrace()[1]['function'];
}

/**
* Converts the name of a model class to the name of the relation of this resource on another model
*
* @param string $resourceName The name of the resource we are dealing with
* @param string $relationType The type of relation - ie.. one to.. X ('one', 'many')
* @return string The name of the relation, as it would appear inside an eloquent model
*/
public static function modelRelationName($resourceName, $relationType = 'many')
{
if ($relationType == 'many') {
return lcfirst(Str::plural(class_basename($resourceName)));
} elseif ($relationType == 'one') {
return lcfirst(class_basename($resourceName));
} else {
return '';
}
}
}
5 changes: 3 additions & 2 deletions src/Http/Controllers/Features/RestfulControllerTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use App\Transformers\BaseTransformer;
use Illuminate\Http\Request;
use Specialtactics\L5Api\Helpers;

trait RestfulControllerTrait
{
Expand Down Expand Up @@ -111,14 +112,14 @@ protected function prependResponseMessage($response, $message)
protected function getChildRelationNameForParent($parent, $child)
{
// Try model plural name
$manyName = model_relation_name($child, 'many');
$manyName = Helpers::modelRelationName($child, 'many');

if (method_exists($parent, $manyName)) {
return $manyName;
}

// Try model singular name
$oneName = model_relation_name($child, 'one');
$oneName = Helpers::modelRelationName($child, 'one');

if (method_exists($parent, $oneName)) {
return $oneName;
Expand Down
5 changes: 3 additions & 2 deletions src/Http/Controllers/RestfulChildController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Specialtactics\L5Api\Helpers;

class RestfulChildController extends BaseRestfulController
{
Expand Down Expand Up @@ -54,7 +55,7 @@ public function getAll($uuid, Request $request)
$this->authorizeUserAction($this->parentAbilitiesRequired['view'], $parentResource);

$model = static::$model;
$resourceRelationName = model_relation_name($model);
$resourceRelationName = Helpers::modelRelationName($model);

// Form model's with relations for parent query
$withArray = [];
Expand Down Expand Up @@ -91,7 +92,7 @@ public function getOneFromParent($uuid, Request $request)
$this->authorizeUserAction($this->parentAbilitiesRequired['view'], $parentResource);

$model = static::$model;
$resourceRelationName = model_relation_name($model, 'one');
$resourceRelationName = Helpers::modelRelationName($model, 'one');

// Form model's with relations for parent query
$withArray = [];
Expand Down
3 changes: 2 additions & 1 deletion src/Http/Middleware/SnakeCaseInputParameterKeys.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Closure;
use Symfony\Component\HttpFoundation\ParameterBag;
use Specialtactics\L5Api\Helpers;

/**
* Class SnakeCaseInputParameterKeys
Expand Down Expand Up @@ -61,7 +62,7 @@ protected function processParamBag(ParameterBag $bag)
$parameters = $bag->all();

if (! empty($parameters) && count($parameters) > 0) {
$parameters = snake_case_array_keys($parameters);
$parameters = Helpers::snakeCaseArrayKeys($parameters);

$bag->replace($parameters);
}
Expand Down

0 comments on commit f4f1964

Please sign in to comment.