Last active
July 5, 2017 05:10
-
-
Save paulofreitas/fee8d27e526ff770f7fcad6a13232866 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use DB; | |
trait ExtendedModel | |
{ | |
public static function getColumnInfo($column) | |
{ | |
$model = new static; | |
$columnMetadata = DB::selectOne( | |
DB::raw(sprintf("SHOW COLUMNS FROM %s WHERE Field = ?", $model->getTable())), | |
[$column] | |
); | |
if (!$columnMetadata) { | |
throw new UnexpectedValueException("Unknown column '{$column}'"); | |
} | |
preg_match_all("/'(.*?)'/", $columnMetadata->Type, $matches); | |
if (strstr($columnMetadata->Type, 'enum')) { | |
$columnMetadata->Values = $matches[1]; | |
} | |
if (strstr($columnMetadata->Type, 'set')) { | |
$columnMetadata->Members = $matches[1]; | |
} | |
return $columnMetadata; | |
} | |
public static function getEnumColumnValues($column) | |
{ | |
return static::getColumnInfo($column)->Values; | |
} | |
public static function getEnumColumnValuesAsJson($column, $nested = false) | |
{ | |
$values = static::getEnumColumnValues($column); | |
if ($nested) { | |
collect($values) | |
->groupBy(function ($value) { | |
return implode('.', explode('_', $value, -1)); | |
}) | |
->map(function ($items) { | |
return collect($items) | |
->map(function ($value) { | |
return array_last(explode('_', $value)); | |
}) | |
->all(); | |
}) | |
->each(function ($items, $key) use (&$nestedValues) { | |
array_set($nestedValues, $key, $items); | |
}); | |
$values = count($nestedValues) > 1 ? $nestedValues : end($nestedValues); | |
} | |
return collect($values)->toJson(); | |
} | |
} | |
/* | |
class SomeModel extends Eloquent | |
{ | |
use ExtendedModel; | |
} | |
$values_json = SomeModel::getEnumColumnValuesAsJson('column_name', true); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment