70 lines
2.1 KiB
PHP
70 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace App\Domain\Ingredients;
|
|
|
|
use App\Domain\Controller;
|
|
use App\Helpers\UploadFiles;
|
|
use App\Http\JSONResponse;
|
|
use App\Http\Request;
|
|
|
|
class IngredientsAPIController extends Controller {
|
|
|
|
public static function defineRoutes(): array
|
|
{
|
|
return [
|
|
self::Route( routeUrl: '/api/ingredients/create', routeName: 'api->ingredients->create', routeAction: 'create', routeMethods: ['POST'] ),
|
|
self::Route( routeUrl: '/api/ingredients/edit', routeName: 'api->ingredients->edit', routeAction: 'edit', routeMethods: ['POST'] ),
|
|
];
|
|
|
|
}
|
|
|
|
public function create(){
|
|
|
|
$name = Request::post( 'name' );
|
|
$fileNameField = "image";
|
|
if( !$name || $name == "" )
|
|
JSONResponse::sendError( [ 'error' => 'Name not defined' ] );
|
|
|
|
$urlOrError = UploadFiles::uploadFile( $fileNameField );
|
|
if( is_int( $urlOrError ) ){
|
|
JSONResponse::sendError( [ 'error' => $urlOrError ] );
|
|
}
|
|
|
|
$ingredient = new Ingredient();
|
|
|
|
$ingredient->num_ingredient = 0;
|
|
$ingredient->nom_ingredient = $name;
|
|
$ingredient->photo_ingredient = $urlOrError;
|
|
|
|
if( !new IngredientRepository()->add( $ingredient ) )
|
|
JSONResponse::sendError( [ 'error' => 'An error occured while adding ingredient' ] );
|
|
|
|
JSONResponse::sendSuccess( [ 'image_url' => $urlOrError ] );
|
|
|
|
}
|
|
|
|
public function edit(){
|
|
|
|
$id = Request::post( 'id' ) ?? 0;
|
|
$ingredient = new IngredientRepository()->getByID( $id );
|
|
if( !$ingredient )
|
|
JSONResponse::sendError( [ 'error' => 'Ingredient not found' ] );
|
|
|
|
$name = Request::post( 'name' );
|
|
$fileNameField = "image";
|
|
|
|
if( $name ) {
|
|
$ingredient->nom_ingredient = $name;
|
|
}
|
|
|
|
$urlOrError = UploadFiles::uploadFile( $fileNameField );
|
|
if( !is_int( $urlOrError ) ){
|
|
$ingredient->photo_ingredient = $urlOrError;
|
|
}
|
|
|
|
if( !new IngredientRepository()->update( $ingredient ) )
|
|
JSONResponse::sendError( [ 'error' => 'An error occured while updating ingredient' ] );
|
|
|
|
JSONResponse::sendSuccess( [] );
|
|
}
|
|
} |