Commit d68905ba by Lech Sawon

Initial commit

parents
# In all environments, the following files are loaded if they exist,
# the latter taking precedence over the former:
#
# * .env contains default values for the environment variables needed by the app
# * .env.local uncommitted file with local overrides
# * .env.$APP_ENV committed environment-specific defaults
# * .env.$APP_ENV.local uncommitted environment-specific overrides
#
# Real environment variables win over .env files.
#
# DO NOT DEFINE PRODUCTION SECRETS IN THIS FILE NOR IN ANY OTHER COMMITTED FILES.
#
# Run "composer dump-env prod" to compile .env files for production use (requires symfony/flex >=1.2).
# https://symfony.com/doc/current/best_practices.html#use-environment-variables-for-infrastructure-configuration
DB_PASS=database_password
###> symfony/framework-bundle ###
APP_ENV=dev
APP_SECRET=6f2878f85842ad973667e9ed8a704b64
#TRUSTED_PROXIES=127.0.0.0/8,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16
#TRUSTED_HOSTS='^(localhost|example\.com)$'
###< symfony/framework-bundle ###
###> symfony/mailer ###
# MAILER_DSN=smtp://localhost
###< symfony/mailer ###
###> doctrine/doctrine-bundle ###
# Format described at https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url
# IMPORTANT: You MUST configure your server version, either here or in config/packages/doctrine.yaml
#
# DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db"
# DATABASE_URL="mysql://db_user:db_password@127.0.0.1:3306/db_name?serverVersion=5.7"
DATABASE_URL="postgresql://symfony:ChangeMe@127.0.0.1:5432/app?serverVersion=13&charset=utf8"
###< doctrine/doctrine-bundle ###
# define your env variables for the test env here
KERNEL_CLASS='App\Kernel'
APP_SECRET='$ecretf0rt3st'
SYMFONY_DEPRECATIONS_HELPER=999999
PANTHER_APP_ENV=panther
PANTHER_ERROR_SCREENSHOT_DIR=./var/error-screenshots
.env
.idea
###> symfony/framework-bundle ###
/.env.local
/.env.local.php
/.env.*.local
/config/secrets/prod/prod.decrypt.private.php
/public/bundles/
/var/
/vendor/
###< symfony/framework-bundle ###
###> symfony/phpunit-bridge ###
.phpunit.result.cache
/phpunit.xml
###< symfony/phpunit-bridge ###
###> phpunit/phpunit ###
/phpunit.xml
.phpunit.result.cache
###< phpunit/phpunit ###
FROM webdevops/php-nginx-dev:7.4
WORKDIR /app
RUN sed -i '/xdebug.profiler_output_dir/d' /usr/local/etc/php/conf.d/98-webdevops.ini
RUN sed -i '/xdebug.remote_connect_back/d' /usr/local/etc/php/conf.d/98-webdevops.ini
RUN sed -i '/xdebug.remote_enable/d' /usr/local/etc/php/conf.d/98-webdevops.ini
#!/usr/bin/env php
<?php
use App\Kernel;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\ErrorHandler\Debug;
if (!in_array(PHP_SAPI, ['cli', 'phpdbg', 'embed'], true)) {
echo 'Warning: The console should be invoked via the CLI version of PHP, not the '.PHP_SAPI.' SAPI'.PHP_EOL;
}
set_time_limit(0);
require dirname(__DIR__).'/vendor/autoload.php';
if (!class_exists(Application::class)) {
throw new LogicException('You need to add "symfony/framework-bundle" as a Composer dependency.');
}
$input = new ArgvInput();
if (null !== $env = $input->getParameterOption(['--env', '-e'], null, true)) {
putenv('APP_ENV='.$_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = $env);
}
if ($input->hasParameterOption('--no-debug', true)) {
putenv('APP_DEBUG='.$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = '0');
}
require dirname(__DIR__).'/config/bootstrap.php';
if ($_SERVER['APP_DEBUG']) {
umask(0000);
if (class_exists(Debug::class)) {
Debug::enable();
}
}
$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
$application = new Application($kernel);
$application->run($input);
#!/usr/bin/env php
<?php
if (!ini_get('date.timezone')) {
ini_set('date.timezone', 'UTC');
}
if (is_file(dirname(__DIR__).'/vendor/phpunit/phpunit/phpunit')) {
define('PHPUNIT_COMPOSER_INSTALL', dirname(__DIR__).'/vendor/autoload.php');
require PHPUNIT_COMPOSER_INSTALL;
PHPUnit\TextUI\Command::main();
} else {
if (!is_file(dirname(__DIR__).'/vendor/symfony/phpunit-bridge/bin/simple-phpunit.php')) {
echo "Unable to find the `simple-phpunit.php` script in `vendor/symfony/phpunit-bridge/bin/`.\n";
exit(1);
}
require dirname(__DIR__).'/vendor/symfony/phpunit-bridge/bin/simple-phpunit.php';
}
{
"type": "project",
"license": "proprietary",
"require": {
"php": ">=7.1.3",
"ext-ctype": "*",
"ext-iconv": "*",
"composer/package-versions-deprecated": "1.11.99.4",
"doctrine/annotations": "^1.0",
"doctrine/doctrine-bundle": "^2.4",
"doctrine/doctrine-migrations-bundle": "^3.2",
"doctrine/orm": "^2.10",
"phpdocumentor/reflection-docblock": "^5.3",
"sensio/framework-extra-bundle": "^5.1",
"symfony/asset": "4.4.*",
"symfony/console": "4.4.*",
"symfony/dotenv": "4.4.*",
"symfony/expression-language": "4.4.*",
"symfony/flex": "^1.3.1",
"symfony/form": "4.4.*",
"symfony/framework-bundle": "4.4.*",
"symfony/http-client": "4.4.*",
"symfony/intl": "4.4.*",
"symfony/mailer": "4.4.*",
"symfony/monolog-bundle": "^3.1",
"symfony/process": "4.4.*",
"symfony/property-access": "4.4.*",
"symfony/property-info": "4.4.*",
"symfony/proxy-manager-bridge": "4.4.*",
"symfony/security-bundle": "4.4.*",
"symfony/serializer": "4.4.*",
"symfony/translation": "4.4.*",
"symfony/twig-bundle": "4.4.*",
"symfony/validator": "4.4.*",
"symfony/web-link": "4.4.*",
"symfony/yaml": "4.4.*",
"twig/extra-bundle": "^2.12|^3.0",
"twig/twig": "^2.12|^3.0"
},
"require-dev": {
"phpunit/phpunit": "^9.5",
"symfony/browser-kit": "4.4.*",
"symfony/css-selector": "4.4.*",
"symfony/debug-bundle": "4.4.*",
"symfony/maker-bundle": "^1.0",
"symfony/phpunit-bridge": "^5.3",
"symfony/stopwatch": "4.4.*",
"symfony/web-profiler-bundle": "4.4.*"
},
"config": {
"preferred-install": {
"*": "dist"
},
"sort-packages": true
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"App\\Tests\\": "tests/"
}
},
"replace": {
"paragonie/random_compat": "2.*",
"symfony/polyfill-ctype": "*",
"symfony/polyfill-iconv": "*",
"symfony/polyfill-php71": "*",
"symfony/polyfill-php70": "*",
"symfony/polyfill-php56": "*"
},
"scripts": {
"auto-scripts": {
"cache:clear": "symfony-cmd",
"assets:install %PUBLIC_DIR%": "symfony-cmd"
},
"post-install-cmd": [
"@auto-scripts"
],
"post-update-cmd": [
"@auto-scripts"
]
},
"conflict": {
"symfony/symfony": "*"
},
"extra": {
"symfony": {
"allow-contrib": false,
"require": "4.4.*"
}
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
<?php
use Symfony\Component\Dotenv\Dotenv;
require dirname(__DIR__).'/vendor/autoload.php';
if (!class_exists(Dotenv::class)) {
throw new LogicException('Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.');
}
// Load cached env vars if the .env.local.php file exists
// Run "composer dump-env prod" to create it (requires symfony/flex >=1.2)
if (is_array($env = @include dirname(__DIR__).'/.env.local.php') && (!isset($env['APP_ENV']) || ($_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? $env['APP_ENV']) === $env['APP_ENV'])) {
(new Dotenv(false))->populate($env);
} else {
// load all the .env files
(new Dotenv(false))->loadEnv(dirname(__DIR__).'/.env');
}
$_SERVER += $_ENV;
$_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = ($_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? null) ?: 'dev';
$_SERVER['APP_DEBUG'] = $_SERVER['APP_DEBUG'] ?? $_ENV['APP_DEBUG'] ?? 'prod' !== $_SERVER['APP_ENV'];
$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = (int) $_SERVER['APP_DEBUG'] || filter_var($_SERVER['APP_DEBUG'], FILTER_VALIDATE_BOOLEAN) ? '1' : '0';
<?php
return [
Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle::class => ['all' => true],
Symfony\Bundle\TwigBundle\TwigBundle::class => ['all' => true],
Symfony\Bundle\WebProfilerBundle\WebProfilerBundle::class => ['dev' => true, 'test' => true],
Symfony\Bundle\MonologBundle\MonologBundle::class => ['all' => true],
Symfony\Bundle\DebugBundle\DebugBundle::class => ['dev' => true],
Symfony\Bundle\MakerBundle\MakerBundle::class => ['dev' => true],
Doctrine\Bundle\DoctrineBundle\DoctrineBundle::class => ['all' => true],
Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle::class => ['all' => true],
Symfony\Bundle\SecurityBundle\SecurityBundle::class => ['all' => true],
Twig\Extra\TwigExtraBundle\TwigExtraBundle::class => ['all' => true],
];
framework:
cache:
# Unique name of your app: used to compute stable namespaces for cache keys.
#prefix_seed: your_vendor_name/app_name
# The "app" cache stores to the filesystem by default.
# The data in this cache should persist between deploys.
# Other options include:
# Redis
#app: cache.adapter.redis
#default_redis_provider: redis://localhost
# APCu (not recommended with heavy random-write workloads as memory fragmentation can cause perf issues)
#app: cache.adapter.apcu
# Namespaced pools use the above "app" backend by default
#pools:
#my.dedicated.cache: null
debug:
# Forwards VarDumper Data clones to a centralized server allowing to inspect dumps on CLI or in your browser.
# See the "server:dump" command to start a new server.
dump_destination: "tcp://%env(VAR_DUMPER_SERVER)%"
monolog:
handlers:
main:
type: stream
path: "%kernel.logs_dir%/%kernel.environment%.log"
level: debug
channels: ["!event"]
# uncomment to get logging in your browser
# you may have to allow bigger header sizes in your Web server configuration
#firephp:
# type: firephp
# level: info
#chromephp:
# type: chromephp
# level: info
console:
type: console
process_psr_3_messages: false
channels: ["!event", "!doctrine", "!console"]
web_profiler:
toolbar: true
intercept_redirects: false
framework:
profiler: { only_exceptions: false }
doctrine:
dbal:
url: '%env(resolve:DATABASE_URL)%'
# IMPORTANT: You MUST configure your server version,
# either here or in the DATABASE_URL env var (see .env file)
#server_version: '13'
orm:
auto_generate_proxy_classes: true
naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
auto_mapping: true
mappings:
App:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: App
doctrine_migrations:
migrations_paths:
# namespace is arbitrary but should be different from App\Migrations
# as migrations classes should NOT be autoloaded
'DoctrineMigrations': '%kernel.project_dir%/migrations'
enable_profiler: '%kernel.debug%'
# see https://symfony.com/doc/current/reference/configuration/framework.html
framework:
secret: '%env(APP_SECRET)%'
#csrf_protection: true
#http_method_override: true
# Enables session support. Note that the session will ONLY be started if you read or write from it.
# Remove or comment this section to explicitly disable session support.
session:
handler_id: null
cookie_secure: auto
cookie_samesite: lax
#esi: true
#fragments: true
php_errors:
log: true
framework:
mailer:
dsn: '%env(MAILER_DSN)%'
# As of Symfony 5.1, deprecations are logged in the dedicated "deprecation" channel when it exists
#monolog:
# channels: [deprecation]
# handlers:
# deprecation:
# type: stream
# channels: [deprecation]
# path: php://stderr
doctrine:
orm:
auto_generate_proxy_classes: false
query_cache_driver:
type: pool
pool: doctrine.system_cache_pool
result_cache_driver:
type: pool
pool: doctrine.result_cache_pool
framework:
cache:
pools:
doctrine.result_cache_pool:
adapter: cache.app
doctrine.system_cache_pool:
adapter: cache.system
monolog:
handlers:
main:
type: fingers_crossed
action_level: error
handler: nested
excluded_http_codes: [404, 405]
buffer_size: 50 # How many messages should be saved? Prevent memory leaks
nested:
type: stream
path: php://stderr
level: debug
formatter: monolog.formatter.json
console:
type: console
process_psr_3_messages: false
channels: ["!event", "!doctrine"]
framework:
router:
strict_requirements: null
framework:
router:
utf8: true
security:
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
users_in_memory: { memory: null }
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: lazy
provider: users_in_memory
# activate different ways to authenticate
# https://symfony.com/doc/current/security.html#firewalls-authentication
# https://symfony.com/doc/current/security/impersonating_user.html
# switch_user: true
# Easy way to control access for large sections of your site
# Note: Only the *first* access control that matches will be used
access_control:
# - { path: ^/admin, roles: ROLE_ADMIN }
# - { path: ^/profile, roles: ROLE_USER }
sensio_framework_extra:
router:
annotations: false
doctrine:
dbal:
# "TEST_TOKEN" is typically set by ParaTest
dbname_suffix: '_test%env(default::TEST_TOKEN)%'
framework:
test: true
session:
storage_id: session.storage.mock_file
monolog:
handlers:
main:
type: fingers_crossed
action_level: error
handler: nested
excluded_http_codes: [404, 405]
channels: ["!event"]
nested:
type: stream
path: "%kernel.logs_dir%/%kernel.environment%.log"
level: debug
twig:
strict_variables: true
framework:
validation:
not_compromised_password: false
web_profiler:
toolbar: false
intercept_redirects: false
framework:
profiler: { collect: false }
framework:
default_locale: en
translator:
default_path: '%kernel.project_dir%/translations'
fallbacks:
- en
twig:
default_path: '%kernel.project_dir%/templates'
debug: '%kernel.debug%'
strict_variables: '%kernel.debug%'
exception_controller: null
framework:
validation:
email_validation_mode: html5
# Enables validator auto-mapping support.
# For instance, basic validation constraints will be inferred from Doctrine's metadata.
#auto_mapping:
# App\Entity\: []
<?php
if (file_exists(dirname(__DIR__).'/var/cache/prod/srcApp_KernelProdContainer.preload.php')) {
require dirname(__DIR__).'/var/cache/prod/srcApp_KernelProdContainer.preload.php';
}
if (file_exists(dirname(__DIR__).'/var/cache/prod/App_KernelProdContainer.preload.php')) {
require dirname(__DIR__).'/var/cache/prod/App_KernelProdContainer.preload.php';
}
#index:
# path: /
# controller: App\Controller\DefaultController::index
controllers:
resource: ../../src/Controller/
type: annotation
kernel:
resource: ../../src/Kernel.php
type: annotation
_errors:
resource: '@FrameworkBundle/Resources/config/routing/errors.xml'
prefix: /_error
web_profiler_wdt:
resource: '@WebProfilerBundle/Resources/config/routing/wdt.xml'
prefix: /_wdt
web_profiler_profiler:
resource: '@WebProfilerBundle/Resources/config/routing/profiler.xml'
prefix: /_profiler
# This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.
# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
resource: '../src/'
exclude:
- '../src/DependencyInjection/'
- '../src/Entity/'
- '../src/Kernel.php'
- '../src/Tests/'
# controllers are imported separately to make sure services can be injected
# as action arguments even if you don't extend any base controller class
App\Controller\:
resource: '../src/Controller/'
tags: ['controller.service_arguments']
# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones
version: '3'
services:
backend:
build: .
ports:
- 80:80
expose:
- 9003
environment:
WEB_DOCUMENT_ROOT: /app/public
WEB_DOCUMENT_INDEX: index.php
PHP_DISPLAY_ERRORS: 1
XDEBUG_CLIENT_PORT: 9003
XDEBUG_CLIENT_HOST: host.docker.internal
volumes:
- "./:/app:delegated"
extra_hosts:
- "host.docker.internal:host-gateway"
depends_on:
- db
networks:
- internal
db:
image: postgres:latest
ports:
- 5432:5432
volumes:
- symfony-course-db-vol:/var/lib/postgresql/data
environment:
POSTGRES_DB: symfony-course
POSTGRES_PASSWORD: ${DB_PASS}
networks:
- internal
networks:
internal:
external: false
volumes:
symfony-course-db-vol: ~
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20211025105819 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
$this->addSql('CREATE SEQUENCE room_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE TABLE room (id INT NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY(id))');
}
public function down(Schema $schema): void
{
$this->addSql('DROP SEQUENCE room_id_seq CASCADE');
$this->addSql('DROP TABLE room');
}
}
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20211025125303 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
$this->addSql('CREATE SEQUENCE reservation_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE TABLE reservation (id INT NOT NULL, room_id INT NOT NULL, date_from TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, date_end TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, PRIMARY KEY(id))');
}
public function down(Schema $schema): void
{
$this->addSql('DROP SEQUENCE reservation_id_seq CASCADE');
$this->addSql('DROP TABLE reservation');
}
}
<?php
use App\Kernel;
use Symfony\Component\ErrorHandler\Debug;
use Symfony\Component\HttpFoundation\Request;
require dirname(__DIR__).'/config/bootstrap.php';
if ($_SERVER['APP_DEBUG']) {
umask(0000);
Debug::enable();
}
if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? false) {
Request::setTrustedProxies(explode(',', $trustedProxies), Request::HEADER_X_FORWARDED_FOR | Request::HEADER_X_FORWARDED_PORT | Request::HEADER_X_FORWARDED_PROTO);
}
if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? false) {
Request::setTrustedHosts([$trustedHosts]);
}
$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
<?php
declare(strict_types=1);
namespace App\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class LuckyController
{
/**
* @Route("/lucky/number", name="app_lucky_number")
*/
public function number(Request $request): Response
{
$number = random_int(0, 100);
return new Response(
'<html><body>Lucky number: '.$number.'</body></html>'
);
}
}
<?php
namespace App\Controller;
use App\Entity\Reservation;
use App\Form\ReservationType;
use App\Repository\ReservationRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("/reservation")
*/
class ReservationController extends AbstractController
{
/**
* @Route("/", name="reservation_index", methods={"GET"})
*/
public function index(ReservationRepository $reservationRepository): Response
{
return $this->render('reservation/index.html.twig', [
'reservations' => $reservationRepository->findAll(),
]);
}
/**
* @Route("/new", name="reservation_new", methods={"GET","POST"})
*/
public function new(Request $request): Response
{
$reservation = new Reservation();
$form = $this->createForm(ReservationType::class, $reservation);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($reservation);
$entityManager->flush();
return $this->redirectToRoute('reservation_index', [], Response::HTTP_SEE_OTHER);
}
return $this->render('reservation/new.html.twig', [
'reservation' => $reservation,
'form' => $form->createView(),
]);
}
/**
* @Route("/{id}", name="reservation_show", methods={"GET"})
*/
public function show(Reservation $reservation): Response
{
return $this->render('reservation/show.html.twig', [
'reservation' => $reservation,
]);
}
/**
* @Route("/{id}/edit", name="reservation_edit", methods={"GET","POST"})
*/
public function edit(Request $request, Reservation $reservation): Response
{
$form = $this->createForm(ReservationType::class, $reservation);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('reservation_index', [], Response::HTTP_SEE_OTHER);
}
return $this->render('reservation/edit.html.twig', [
'reservation' => $reservation,
'form' => $form->createView(),
]);
}
/**
* @Route("/{id}", name="reservation_delete", methods={"POST"})
*/
public function delete(Request $request, Reservation $reservation): Response
{
if ($this->isCsrfTokenValid('delete'.$reservation->getId(), $request->request->get('_token'))) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($reservation);
$entityManager->flush();
}
return $this->redirectToRoute('reservation_index', [], Response::HTTP_SEE_OTHER);
}
}
<?php
namespace App\Controller;
use App\Entity\Room;
use App\Form\RoomType;
use App\Repository\RoomRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("/room")
*/
class RoomController extends AbstractController
{
/**
* @Route("/", name="room_index", methods={"GET"})
*/
public function index(RoomRepository $roomRepository): Response
{
return $this->render('room/index.html.twig', [
'rooms' => $roomRepository->findAll(),
]);
}
/**
* @Route("/new", name="room_new", methods={"GET","POST"})
*/
public function new(Request $request): Response
{
$room = new Room();
$form = $this->createForm(RoomType::class, $room);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($room);
$entityManager->flush();
return $this->redirectToRoute('room_index', [], Response::HTTP_SEE_OTHER);
}
return $this->render('room/new.html.twig', [
'room' => $room,
'form' => $form->createView(),
]);
}
/**
* @Route("/{id}", name="room_show", methods={"GET"})
*/
public function show(Room $room): Response
{
return $this->render('room/show.html.twig', [
'room' => $room,
]);
}
/**
* @Route("/{id}/edit", name="room_edit", methods={"GET","POST"})
*/
public function edit(Request $request, Room $room): Response
{
$form = $this->createForm(RoomType::class, $room);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('room_index', [], Response::HTTP_SEE_OTHER);
}
return $this->render('room/edit.html.twig', [
'room' => $room,
'form' => $form->createView(),
]);
}
/**
* @Route("/{id}", name="room_delete", methods={"POST"})
*/
public function delete(Request $request, Room $room): Response
{
if ($this->isCsrfTokenValid('delete'.$room->getId(), $request->request->get('_token'))) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($room);
$entityManager->flush();
}
return $this->redirectToRoute('room_index', [], Response::HTTP_SEE_OTHER);
}
}
<?php
declare(strict_types=1);
namespace App\Controller;
final class TEst
{
}
<?php
namespace App\Entity;
use App\Repository\ReservationRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=ReservationRepository::class)
*/
class Reservation
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="integer")
*/
private $roomId;
/**
* @ORM\Column(type="datetime")
*/
private $dateFrom;
/**
* @ORM\Column(type="datetime")
*/
private $dateEnd;
public function getId(): ?int
{
return $this->id;
}
public function getRoomId(): ?int
{
return $this->roomId;
}
public function setRoomId(int $roomId): self
{
$this->roomId = $roomId;
return $this;
}
public function getDateFrom(): ?\DateTimeInterface
{
return $this->dateFrom;
}
public function setDateFrom(\DateTimeInterface $dateFrom): self
{
$this->dateFrom = $dateFrom;
return $this;
}
public function getDateEnd(): ?\DateTimeInterface
{
return $this->dateEnd;
}
public function setDateEnd(\DateTimeInterface $dateEnd): self
{
$this->dateEnd = $dateEnd;
return $this;
}
}
<?php
namespace App\Entity;
use App\Repository\RoomRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=RoomRepository::class)
*/
class Room
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $name;
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
}
<?php
namespace App\Form;
use App\Entity\Reservation;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ReservationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('roomId')
->add('dateFrom')
->add('dateEnd')
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Reservation::class,
]);
}
}
<?php
namespace App\Form;
use App\Entity\Room;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class RoomType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('name')
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Room::class,
]);
}
}
<?php
namespace App;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\RouteCollectionBuilder;
class Kernel extends BaseKernel
{
use MicroKernelTrait;
private const CONFIG_EXTS = '.{php,xml,yaml,yml}';
public function registerBundles(): iterable
{
$contents = require $this->getProjectDir().'/config/bundles.php';
foreach ($contents as $class => $envs) {
if ($envs[$this->environment] ?? $envs['all'] ?? false) {
yield new $class();
}
}
}
public function getProjectDir(): string
{
return \dirname(__DIR__);
}
protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader): void
{
$container->addResource(new FileResource($this->getProjectDir().'/config/bundles.php'));
$container->setParameter('container.dumper.inline_class_loader', \PHP_VERSION_ID < 70400 || $this->debug);
$container->setParameter('container.dumper.inline_factories', true);
$confDir = $this->getProjectDir().'/config';
$loader->load($confDir.'/{packages}/*'.self::CONFIG_EXTS, 'glob');
$loader->load($confDir.'/{packages}/'.$this->environment.'/*'.self::CONFIG_EXTS, 'glob');
$loader->load($confDir.'/{services}'.self::CONFIG_EXTS, 'glob');
$loader->load($confDir.'/{services}_'.$this->environment.self::CONFIG_EXTS, 'glob');
}
protected function configureRoutes(RouteCollectionBuilder $routes): void
{
$confDir = $this->getProjectDir().'/config';
$routes->import($confDir.'/{routes}/'.$this->environment.'/*'.self::CONFIG_EXTS, '/', 'glob');
$routes->import($confDir.'/{routes}/*'.self::CONFIG_EXTS, '/', 'glob');
$routes->import($confDir.'/{routes}'.self::CONFIG_EXTS, '/', 'glob');
}
}
<?php
namespace App\Repository;
use App\Entity\Reservation;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @method Reservation|null find($id, $lockMode = null, $lockVersion = null)
* @method Reservation|null findOneBy(array $criteria, array $orderBy = null)
* @method Reservation[] findAll()
* @method Reservation[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class ReservationRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Reservation::class);
}
// /**
// * @return Reservation[] Returns an array of Reservation objects
// */
/*
public function findByExampleField($value)
{
return $this->createQueryBuilder('r')
->andWhere('r.exampleField = :val')
->setParameter('val', $value)
->orderBy('r.id', 'ASC')
->setMaxResults(10)
->getQuery()
->getResult()
;
}
*/
/*
public function findOneBySomeField($value): ?Reservation
{
return $this->createQueryBuilder('r')
->andWhere('r.exampleField = :val')
->setParameter('val', $value)
->getQuery()
->getOneOrNullResult()
;
}
*/
}
<?php
namespace App\Repository;
use App\Entity\Room;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @method Room|null find($id, $lockMode = null, $lockVersion = null)
* @method Room|null findOneBy(array $criteria, array $orderBy = null)
* @method Room[] findAll()
* @method Room[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class RoomRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Room::class);
}
// /**
// * @return Room[] Returns an array of Room objects
// */
/*
public function findByExampleField($value)
{
return $this->createQueryBuilder('r')
->andWhere('r.exampleField = :val')
->setParameter('val', $value)
->orderBy('r.id', 'ASC')
->setMaxResults(10)
->getQuery()
->getResult()
;
}
*/
/*
public function findOneBySomeField($value): ?Room
{
return $this->createQueryBuilder('r')
->andWhere('r.exampleField = :val')
->setParameter('val', $value)
->getQuery()
->getOneOrNullResult()
;
}
*/
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{% block title %}Welcome!{% endblock %}</title>
{# Run `composer require symfony/webpack-encore-bundle`
and uncomment the following Encore helpers to start using Symfony UX #}
{% block stylesheets %}
{#{{ encore_entry_link_tags('app') }}#}
{% endblock %}
{% block javascripts %}
{#{{ encore_entry_script_tags('app') }}#}
{% endblock %}
</head>
<body>
{% block body %}{% endblock %}
</body>
</html>
<form method="post" action="{{ path('reservation_delete', {'id': reservation.id}) }}" onsubmit="return confirm('Are you sure you want to delete this item?');">
<input type="hidden" name="_token" value="{{ csrf_token('delete' ~ reservation.id) }}">
<button class="btn">Delete</button>
</form>
{{ form_start(form) }}
{{ form_widget(form) }}
<button class="btn">{{ button_label|default('Save') }}</button>
{{ form_end(form) }}
{% extends 'base.html.twig' %}
{% block title %}Edit Reservation{% endblock %}
{% block body %}
<h1>Edit Reservation</h1>
{{ include('reservation/_form.html.twig', {'button_label': 'Update'}) }}
<a href="{{ path('reservation_index') }}">back to list</a>
{{ include('reservation/_delete_form.html.twig') }}
{% endblock %}
{% extends 'base.html.twig' %}
{% block title %}Reservation index{% endblock %}
{% block body %}
<h1>Reservation index</h1>
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>RoomId</th>
<th>DateFrom</th>
<th>DateEnd</th>
<th>actions</th>
</tr>
</thead>
<tbody>
{% for reservation in reservations %}
<tr>
<td>{{ reservation.id }}</td>
<td>{{ reservation.roomId }}</td>
<td>{{ reservation.dateFrom ? reservation.dateFrom|date('Y-m-d H:i:s') : '' }}</td>
<td>{{ reservation.dateEnd ? reservation.dateEnd|date('Y-m-d H:i:s') : '' }}</td>
<td>
<a href="{{ path('reservation_show', {'id': reservation.id}) }}">show</a>
<a href="{{ path('reservation_edit', {'id': reservation.id}) }}">edit</a>
</td>
</tr>
{% else %}
<tr>
<td colspan="5">no records found</td>
</tr>
{% endfor %}
</tbody>
</table>
<a href="{{ path('reservation_new') }}">Create new</a>
{% endblock %}
{% extends 'base.html.twig' %}
{% block title %}New Reservation{% endblock %}
{% block body %}
<h1>Create new Reservation</h1>
{{ include('reservation/_form.html.twig') }}
<a href="{{ path('reservation_index') }}">back to list</a>
{% endblock %}
{% extends 'base.html.twig' %}
{% block title %}Reservation{% endblock %}
{% block body %}
<h1>Reservation</h1>
<table class="table">
<tbody>
<tr>
<th>Id</th>
<td>{{ reservation.id }}</td>
</tr>
<tr>
<th>RoomId</th>
<td>{{ reservation.roomId }}</td>
</tr>
<tr>
<th>DateFrom</th>
<td>{{ reservation.dateFrom ? reservation.dateFrom|date('Y-m-d H:i:s') : '' }}</td>
</tr>
<tr>
<th>DateEnd</th>
<td>{{ reservation.dateEnd ? reservation.dateEnd|date('Y-m-d H:i:s') : '' }}</td>
</tr>
</tbody>
</table>
<a href="{{ path('reservation_index') }}">back to list</a>
<a href="{{ path('reservation_edit', {'id': reservation.id}) }}">edit</a>
{{ include('reservation/_delete_form.html.twig') }}
{% endblock %}
<form method="post" action="{{ path('room_delete', {'id': room.id}) }}" onsubmit="return confirm('Are you sure you want to delete this item?');">
<input type="hidden" name="_token" value="{{ csrf_token('delete' ~ room.id) }}">
<button class="btn">Delete</button>
</form>
{{ form_start(form) }}
{{ form_widget(form) }}
<button class="btn">{{ button_label|default('Save') }}</button>
{{ form_end(form) }}
{% extends 'base.html.twig' %}
{% block title %}Edit Room{% endblock %}
{% block body %}
<h1>Edit Room</h1>
{{ include('room/_form.html.twig', {'button_label': 'Update'}) }}
<a href="{{ path('room_index') }}">back to list</a>
{{ include('room/_delete_form.html.twig') }}
{% endblock %}
{% extends 'base.html.twig' %}
{% block title %}Room index{% endblock %}
{% block body %}
<h1>Room index</h1>
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>actions</th>
</tr>
</thead>
<tbody>
{% for room in rooms %}
<tr>
<td>{{ room.id }}</td>
<td>{{ room.name }}</td>
<td>
<a href="{{ path('room_show', {'id': room.id}) }}">show</a>
<a href="{{ path('room_edit', {'id': room.id}) }}">edit</a>
</td>
</tr>
{% else %}
<tr>
<td colspan="3">no records found</td>
</tr>
{% endfor %}
</tbody>
</table>
<a href="{{ path('room_new') }}">Create new</a>
{% endblock %}
{% extends 'base.html.twig' %}
{% block title %}New Room{% endblock %}
{% block body %}
<h1>Create new Room</h1>
{{ include('room/_form.html.twig') }}
<a href="{{ path('room_index') }}">back to list</a>
{% endblock %}
{% extends 'base.html.twig' %}
{% block title %}Room{% endblock %}
{% block body %}
<h1>Room</h1>
<table class="table">
<tbody>
<tr>
<th>Id</th>
<td>{{ room.id }}</td>
</tr>
<tr>
<th>Name</th>
<td>{{ room.name }}</td>
</tr>
</tbody>
</table>
<a href="{{ path('room_index') }}">back to list</a>
<a href="{{ path('room_edit', {'id': room.id}) }}">edit</a>
{{ include('room/_delete_form.html.twig') }}
{% endblock %}
<?php
use Symfony\Component\Dotenv\Dotenv;
require dirname(__DIR__).'/vendor/autoload.php';
if (file_exists(dirname(__DIR__).'/config/bootstrap.php')) {
require dirname(__DIR__).'/config/bootstrap.php';
} elseif (method_exists(Dotenv::class, 'bootEnv')) {
(new Dotenv())->bootEnv(dirname(__DIR__).'/.env');
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment