-
Notifications
You must be signed in to change notification settings - Fork 5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Manter os dados num arquivo #3
Comments
O CSV já está pronto e é bem confiável, datasets-br/state-codes. Usando ele fica simples gerar o código PHP. Abaixo o script gerador (testado!) <?php
$allStates = file_csv('https://raw.githubusercontent.com/datasets-br/state-codes/master/data/br-state-codes.csv');
foreach ($allStates as $item) {
$uf = (object) $item;
$ascName = iconv('utf-8', 'ascii//TRANSLIT', $uf->name);
$clasName = str_replace(' ', '', ucwords($ascName));
if ($uf->idIBGE) file_put_contents("src/$clasName.php", "<?php
namespace Brazanation\States;
class $clasName extends State
{
const CODE = {$uf->idIBGE};
const FULL_NAME = '{$uf->name}';
const SHORT_NAME = '{$uf->subdivision}';
const TIMEZONE = '{$uf->timeZone}';
public function __construct()
{
parent::__construct(
self::FULL_NAME,
self::SHORT_NAME,
self::CODE,
self::TIMEZONE
);
}
}
");
}
/**
* Reads entire CSV file into an array (or associative array or pair of header-content arrays).
* Like build-in file() function, but to CSV handling.
* @param $file string filename.
* @param $opt not-null (can be empty) associative array of options (sep,enclosure,escape,head,assoc,limit)
* @param $length integer same as in fgetcsv().
* @param $context resource same as in fopen().
* @return array (as head and assoc options).
*/
function file_csv($file, $opt=[], $length=0, resource $context=NULL) {
$opt = array_merge(['sep'=>',', 'enclosure'=>'"', 'escape'=>"\\", 'head'=>false, 'assoc'=>true, 'limit'=>0], $opt);
$header = NULL;
$n=0; $nmax=(int)$opt['limit'];
$lines = [];
$h = $context? fopen($file,'r',false,$context): fopen($file,'r');
while( $h && !feof($h) && (!$nmax || $n<$nmax) )
if ( ($r=fgetcsv($h,$length,$opt['sep'],$opt['enclosure'],$opt['escape'])) && $n++>0 )
$lines[] = $opt['assoc']? array_combine($header,$r): $r;
elseif ($n==1)
$header = $r;
return $opt['head']? array($header,$lines): $lines;
} |
This was referenced May 15, 2017
ppKrauss
added a commit
to ppKrauss/php-states
that referenced
this issue
May 17, 2017
PR #7 solve it |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
O que vocês acham de ter os dados dos estados num JSON, XML, YAML, CSV... e gerar as classes a partir de um build script? Ficaria muito mais fácil de manter e manteria uma consistência entre as classes. Poderia até fazer o build gerar as classes de testes unitários.
O cerne, o core, o domínio que o projeto se propõe resolver, ao meu ver, é ter dados das unidades federativas brasileiras, mas atualmente esses dados estão hard-coded em classes sem comportamento (anemic-domain model). Ter essas informações num arquivo com um formato de intercâmbio de dados (XML, YAML, JSON, CSV etc) torna o projeto muito mais flexível, as pessoas poderão usar os dados em diversas aplicações, usa-los cru (raw) ou até criar builds para outras linguagens além do PHP.
The text was updated successfully, but these errors were encountered: