Skip to content

Instantly share code, notes, and snippets.

@danganf
Created October 11, 2018 21:08
Show Gist options
  • Save danganf/dcdfbd1ec2519b69e2a7b5502a4f4d6b to your computer and use it in GitHub Desktop.
Save danganf/dcdfbd1ec2519b69e2a7b5502a4f4d6b to your computer and use it in GitHub Desktop.
<?php
namespace App\Model;
use App\Model\Views\AcomodacaoDetalhes;
use App\Model\Views\Comodidades;
use Illuminate\Database\Eloquent\Model;
class Acomodacao extends Model
{
protected $table = 'acomodacao';
protected $guarded = 'id';
protected $primaryKey = 'id';
public function comodidades() {
return $this->hasMany( Comodidade::class , 'acomodacao_id', 'id' );
}
public function detalhes() {
return $this->hasMany( AcomodacaoDetalhe::class , 'acomodacao_id', 'id' );
}
public function viewComodidades() {
return $this->hasMany( Comodidades::class , 'acomodacao_id', 'id' );
}
public function viewDetalhes() {
return $this->hasMany( AcomodacaoDetalhes::class , 'acomodacao_id', 'id' );
}
public function galeria() {
return $this->hasMany( GaleriaAcomodacao::class , 'acomodacao_id', 'id' );
}
}
<?php
namespace App\Http\Controllers;
use App\MyClass\MyFileSystems;
use App\MyClass\MyFilter;
use App\MyClass\Paginator;
use App\MyClass\Traits\OpenViewController;
use App\Repositories\AcomodacaoRepository;
use App\Repositories\TipoRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class AcomodacaoController extends Controller
{
use OpenViewController;
private $title = 'Acomodações';
private $pathView = 'acomodacoes';
public function criar( Request $request, TipoRepository $tipoRepository ) {
$dados['flags'] = loadFiles('flags');
$dados['tipos'] = $tipoRepository->getAcomodacoes();
$dados['comodidades'] = $tipoRepository->getComodidades();
return $this->openView( 'Criar', $dados );
}
public function editar( Request $request, AcomodacaoRepository $acomodacaoRepository, TipoRepository $tipoRepository, MyFileSystems $myFileSystems ){
$acomID = $request->route('id');
if( !empty( $acomID ) ) {
$pousadaRepository = $request->get('pousadaRepository');
$acomodacao = $pousadaRepository->getAcomodacoes( $acomID, $acomodacaoRepository, $myFileSystems );
if( !empty( $acomodacao ) ){
$acomodacao['comodidades'] = pluckMatriz( $acomodacao['comodidades'], 'tipo_id');
$dados['flags'] = loadFiles('flags');
$dados['dadosBasicos'] = $acomodacao;
$dados['tipos'] = $tipoRepository->getAcomodacoes();
$dados['comodidades'] = $tipoRepository->getComodidades();
return $this->openView( 'Editar', $dados );
}
}
flash('Pagina não encontrada','warning','Ops!')->sweet();
return redirect()->route('acomodacoes.list');
}
public function lista( Request $request, TipoRepository $tipoRepository, Paginator $paginator, MyFilter $myFilter ){
$page = (int)$request->route('page');
$page = ( !empty( $page ) && is_int( $page ) ? $page : 1 );
$pousadaRepository = $request->get('pousadaRepository');
$acomodacoes = $pousadaRepository->getAcomodacoesByFilter( $page, $paginator, $myFilter );
return $this->openView('Lista',[
'acomodacoes' => $acomodacoes,
'filter' => $myFilter->getFilter(),
'paginator' => $paginator,
'flags' => loadFiles('flags'),
'tipos' => $tipoRepository->getAcomodacoes(),
'routeCreate' => route('acomodacoes.create')
]
,'index');
}
}
<?php
namespace App\Repositories;
use App\Model\Acomodacao;
use App\MyClass\MyFileSystems;
use App\Repositories\Contracts\RepositoryAbstract;
use Illuminate\Http\UploadedFile;
class AcomodacaoRepository extends RepositoryAbstract
{
public function __construct( $model = '' ) {
parent::__construct( Acomodacao::class, $model );
return $this;
}
public function syncAcomodacaoDetalhes( $arrayDescricao, $label='DESCRICAO' ){
if( !$this->fails() ) {
$dadosDescricao = [];
foreach ( $arrayDescricao AS $row ) {
$dadosDescricao[$row['lang']] = $row['html'];
}
$detalhesSaves = $this->getAcomodacaoDetalhes($label);
$detalhesSaves = (empty($detalhesSaves) ? [] : pluckMatriz($detalhesSaves, 'lang'));
$keysNews = array_keys($dadosDescricao);
$descAdd = array_diff($keysNews, $detalhesSaves);
$descDel = array_diff($detalhesSaves, $keysNews);
$descUpdt = array_intersect($keysNews, $detalhesSaves);
$modelDetalhes = $this->getModel()->detalhes()->getRelated();
#incluindo novo
foreach ( $descAdd AS $lang ) {
$model = clone $modelDetalhes;
$model->acomodacao_id = $this->get('id');
$model->label = $label;
$model->lang = $lang;
$model->value = $dadosDescricao[$lang];
$model->save();
}
#deletando os q nao existem
foreach ( $descDel AS $lang ) {
$model = clone $modelDetalhes;
$model->where('acomodacao_id', $this->get('id'))
->where('label' , $label)
->where('lang' , $lang)->delete();
}
#atualizando os q existem
foreach ( $descUpdt AS $lang ) {
$model = clone $modelDetalhes;
$model->where('acomodacao_id', $this->get('id'))
->where('label' , $label)
->where('lang' , $lang)
->update(['value' => $dadosDescricao[$lang]]);
}
}
}
public function syncComodidades( $arrayTipos ){
foreach ( $arrayTipos AS $key=>$comodidade ) {$arrayTipos[$key] = (int)$comodidade;}
$tiposSaves = $this->getComodidades();
$tiposSaves = ( empty( $tiposSaves ) ? [] : pluckMatriz($tiposSaves,'tipo_id') );
$tiposAdd = array_diff( $arrayTipos, $tiposSaves );
$tiposDel = array_diff( $tiposSaves, $arrayTipos );
$modelComodidade = $this->getModel()->comodidades()->getRelated();
foreach ( $tiposAdd AS $tipoID ){
$model = clone $modelComodidade;
$model->acomodacao_id = $this->get('id');
$model->tipo_id = $tipoID;
$model->save();
}
foreach ( $tiposDel AS $tipoID ){
$model = clone $modelComodidade;
$model->where('acomodacao_id' , $this->get('id'))->where('tipo_id',$tipoID)->delete();
}
}
public function getComodidades(){
$modelViewComodidades = $this->getModel()->viewComodidades()->getRelated();
return $modelViewComodidades->where('pousada_id' , $this->get('pousada_id'))
->where('acomodacao_id', $this->get('id'))
->where('tipo_status' , 'L')
->select('acomodacao_id','tipo_id','tipo_nome','tipo_status')
->get()->toArray();
}
public function getAcomodacaoDetalhes($label=null){
$modelViewDetalhes = $this->getModel()->viewDetalhes()->getRelated();
$querie = $modelViewDetalhes->where('pousada_id' , $this->get('pousada_id'))
->where('acomodacao_id', $this->get('id') );
if( !empty( $label ) ) {$querie->where('label', $label);}
return $querie->orderBy('label')->select('acomodacao_id','label','lang','value')->get()->toArray();
}
public function deleteAcomodacaoDetalhe( $lang, $label ){
if( !$this->fails() ) {
$this->getModel()->detalhes()->getRelated()->where( 'acomodacao_id', $this->get('id') )->where( 'lang', $lang )->where( 'label', $label )->delete();
}
}
public function getGaleria( MyFileSystems $myFileSystems=null ){
$dados = [];
foreach ( $this->getModel()->galeria->toArray() AS $row ){
$dados[] = [
'path' => ( empty( $myFileSystems ) ? $row['path'] : $myFileSystems->getUrl( $row['path'] ) ),
'size' => $row['size']
];
}
return $dados;
}
public function createImgGallery( UploadedFile $uploadedFile, MyFileSystems $myFileSystems ){
$result = [];
if( !$this->fails() ) {
if( $this->getModel()->galeria()->count() <= 10 ) {
$result = $myFileSystems->saveImgGalleryAcomodacao($uploadedFile, $this->get('id'));
if ( !empty($result) ) {
$galeriaModel = $this->getModel()->galeria()->getRelated();
$galeriaModel->acomodacao_id = $this->get('id');
$galeriaModel->path = $result['path'];
$galeriaModel->size = $uploadedFile->getClientSize();
$this->getModel()->galeria()->save($galeriaModel);
}
}
}
return $result;
}
public function deleteImgGallery( $fileName, MyFileSystems $myFileSystems ){
$result = FALSE;
if( !$this->fails() ) {
$fileName = $myFileSystems->getPathGalleryAcomodacao() . $fileName;
$collection = $this->getModel()->galeria()
->where('acomodacao_id', $this->get('id') )
->where('path', 'LIKE', "%$fileName%" )
->first();
if( !empty( $collection ) ){
$result = $myFileSystems->deleteFile( $collection->path );
if( !empty( $result ) ){
$collection->delete();
}
}
}
return $result;
}
public function delete ()
{
$gallery = $this->getGaleria();
if( !empty( $gallery ) ) {
#App:make = resolvendo dependencias para instancia a classe
$myFileSystems = \App::make(MyFileSystems::class);
foreach ( $gallery AS $row ) {
$myFileSystems->deleteFile( $row['path'] );
}
}
return parent::delete();
}
public function createOrUpdate ($arrayValores)
{
// TODO: Implement createOrUpdate() method.
}
}
<?php
namespace App\MyClass;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\File;
class MyFileSystems
{
private $sessionOpen;
private $diskCloud;
private $diskLocal;
private $pathDefault;
private $pathDisk;
private $imageManager;
private $nameLogo = 'logo.png';
public function __construct ( SessionOpen $sessionOpen, \Illuminate\Contracts\Filesystem\Factory $fs, \Intervention\Image\ImageManagerStatic $image ){
$this->sessionOpen = $sessionOpen;
$this->diskLocal = $fs->disk( 'local' );
$this->diskCloud = $fs->disk( getenv('APP_FILESYSTEM') );
$this->pathDefault = "cliente_" . $this->sessionOpen->get('cliente_id');
$this->pathDisk = $this->diskLocal->getDriver()->getAdapter()->getPathPrefix();
$this->imageManager = $image;
unset( $sessionOpen, $fs, $image );
}
public function saveLogo( $contentFile ){
$pathFile = $this->pathDefault . '/' . $this->nameLogo;
$pathTemp = 'temp'. '/' . $pathFile;
$pathOrigin = $this->pathDisk . $pathTemp;
#criando arquivo local
$this->diskLocal->put( $pathTemp, $this->cleanContentFileImage( $contentFile ) );
#redimencioando imagem
$this->imageResize( $pathOrigin, 200, 150 );
#copiando arquivo para o destino
$this->diskCloud->put( $pathFile, $this->diskLocal->get($pathTemp) );
#apagando pasta local
$this->diskLocal->deleteDirectory( dirname($pathTemp) );
return $pathFile;
}
public function saveImgGalleryAcomodacao( UploadedFile $contentImg, $prefx='' ){
return $this->createImage( $contentImg->getClientOriginalName(), $this->getPathGalleryAcomodacao(), $contentImg->getPathName(), $prefx );
}
public function saveImgGalleryPousada( UploadedFile $contentImg, $prefx='' ){
#salvando original
$retorno = $this->createImage( $contentImg->getClientOriginalName(), $this->getPathOriginalGalleryPousada(), $contentImg->getPathName(), $prefx );
#salvando imagem tratada
$imageToWeb = $this->interventionImgToWeb( $contentImg->getRealPath() );
$this->diskCloud->put( $this->getPathGalleryPousada() . $retorno['nome'], (string) $imageToWeb );
return $retorno;
}
public function deleteFile( $pathFile ){
return $this->diskCloud->delete( $pathFile );
}
private function cleanContentFileImage( $content ){
$image = str_replace('data:image/png;base64,', '', $content);
$image = str_replace(' ', '+', $image);
return base64_decode($image);
}
private function imageResize( $path, $w, $h ){$this->imageManager->make( $path )->resize($w, $h)->save();}
public function getUrlLogo() { return $this->getUrl( $this->nameLogo ); }
public function getUrl( $pathFile="" ) { return $this->diskCloud->url( $pathFile ); }
public function getPathDefault() { return $this->pathDefault; }
public function getPathGalleryAcomodacao() { return $this->pathDefault . '/gallery/acomodacoes/'; }
public function getPathGalleryPousada() { return $this->pathDefault . '/gallery/'; }
public function getPathOriginalGalleryPousada() { return $this->getPathGalleryPousada() . 'original/'; }
private function createImage( $originalName, $pathDestineImage, $pathTemp, $prefx ){
$randName = $prefx . '_' . base_convert(date('is'),20,36) . base_convert(rand(10000,99999),20,36) .'_'. base_convert(rand(1000000,9999999),20,36);
$randName .= '_' . base_convert(date('is'),20,36) . base_convert(rand(10000,99999),20,36) .'_'. base_convert(rand(1000000,9999999),20,36);
$randName .= '.' . File::extension( $originalName );
$pathDestineImage .= $randName;
#copiando arquivo para o destino
$this->diskCloud->put( $pathDestineImage, File::get( $pathTemp ) );
return [ 'path' => $pathDestineImage, 'nome' => $randName ];
}
private function interventionImgToWeb( $pathFullImg ){
$image = $this->imageManager->make( $pathFullImg );
$width = 800;
$height = 600;
$image->width() > $image->height() ? $width=null : $height=null;
$image->orientate()->resize($width, $height, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
return $image->encode();
}
}
<?php
namespace App\Repositories\Contracts;
abstract class RepositoryAbstract implements RepositoryInterface
{
private $model;
function __construct( $modelBind, $model=null )
{
if ( !$model instanceof $modelBind ) {
$model = new $modelBind();
}
if ( is_object( $model ) )
$this->model = $model;
}
public function bindModel( $instanceModel )
{
if ( $instanceModel instanceof $this->model ) {
$this->model = $instanceModel;
}
}
public function set( $campo, $valor )
{
$this->model->$campo = $valor;
return $this;
}
public function get( $campo )
{
$valor = ( isset ( $this->model->$campo ) ? $this->model->$campo : FALSE );
return $valor;
}
public function has($campo)
{
return ( !empty( $this->get($campo) ) ? true : false );
}
public function save()
{
return $this->model->save();
}
public function update( $lista = [ ] )
{
return $this->model->update( $lista );
}
public function delete()
{
return $this->model->delete();
}
public function getLastID()
{
return ( isset ( $this->model->id ) ? $this->model->id : FALSE );
}
public function getModel()
{
return $this->model;
}
public function find( $valor )
{
$result = $this->model->find( $valor );
if( !is_null($result ) ) {
$this->model = $result;
}
return $this;
}
public function increment( $campo )
{
return $this->model->increment( $campo );
}
public function findBy( $campoUnico, $documento ) {
$result = $this->getModel()->where($campoUnico,$documento)->first();
if( !is_null($result ) ) {
$this->model = $result;
}
return $this;
}
public function findAll( $campo, $documento ) {
return $this->getModel()->where($campo,$documento)->get()->toArray();
}
public function all(){
return $this->getModel()->all();
}
public function toArray()
{
return $this->getModel()->toArray();
}
public function fails(){
return ( empty( $this->getModel()->getKey() ) ? TRUE : FALSE );
}
}
<?php
namespace App\Repositories\Contracts;
interface RepositoryInterface
{
public function set( $campo, $valor );
public function get( $campo );
public function has( $campo );
public function save();
public function all();
public function getLastID();
public function getModel();
public function bindModel( $instanceModel );
public function toArray();
public function find( $valor );
public function increment( $campo );
public function createOrUpdate( $arrayValores );
public function fails();
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Tipo extends Model
{
protected $table = 'tipo';
//protected $fillable = array ();
protected $guarded = 'id';
protected $primaryKey = 'id';
}
<?php
namespace App\Repositories;
use App\Model\Tipo;
use App\Repositories\Contracts\RepositoryAbstract;
class TipoRepository extends RepositoryAbstract
{
public function __construct( $model = '' )
{
parent::__construct( Tipo::class, $model );
return $this;
}
public function getAcomodacoes(){
return $this->getModel()
->where( 'status', 'L' )
->where( 'tipo', 'ACOMODACAO' )
->orderBy('nome')->get()->toArray();
}
public function getComodidades(){
return $this->getModel()
->where( 'status', 'L' )
->where( 'tipo', 'COMODIDADE' )
->orderBy('nome')->get()->toArray();
}
public function createOrUpdate($arrayValores)
{
// TODO: Implement createOrUpdate() method.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment