Example #1
0
 /**
  * Bootstrap the Silex application by registering all providers and
  * services and returning a pre-configured Silex Application object.
  *
  */
 public static function bootstrap()
 {
     // front controller
     $app = new \Silex\Application();
     //$app['debug'] = true;
     //declare app globals
     $app['userName'] = null;
     $app['posterID'] = null;
     $app['sqlInsertMessage'] = "INSERT INTO messageboard (posterID, content) VALUES (?, ?)";
     $app['sqlInsertUser'] = "******";
     $app['sqlListMessageBoard'] = "Select mbID, userName, Content, postTS from messageboard mb\n\t\t\t\t\t\t\t\t\t\tjoin users u on mb.posterID = u.UserID order by mbID desc";
     $app['sqlGetMaxID'] = "Select Max(userID) as uid from users where userName = ?";
     $app['sqlCreateDB'] = "CREATE DATABASE IF NOT EXISTS sqlando;";
     $app['sqlCreateTableMessageBoard'] = "use sqlando;\n\t\t\tCREATE TABLE IF NOT EXISTS `messageboard` (\n\t\t\t`mbID` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,\n\t\t\t`posterID` int(11) NOT NULL,\n\t\t\t`Content` varchar(140) NOT NULL,\n\t\t\t`postTS` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n\t\t\tPRIMARY KEY (`mbID`),\n\t\t\tUNIQUE KEY `mbID` (`mbID`)\n\t\t\t\t) ENGINE=InnoDB DEFAULT CHARSET=latin1;";
     $app['sqlCreateTableUsers'] = "use sqlando;\n\t\t\tCREATE TABLE IF NOT EXISTS `users` (\n\t\t\t`userID` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,\n\t\t\t`userName` varchar(250) NOT NULL,\n\t\t\t`loginTS` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n\t\t\tPRIMARY KEY (`userID`),\n\t\t\tUNIQUE KEY `userID` (`userID`)\n\t\t\t) ENGINE=InnoDB DEFAULT CHARSET=latin1;";
     // set up the db provider
     $app->register(new \Silex\Provider\DoctrineServiceProvider(), array('dbs.options' => array('mysql_dts' => array('dbhost' => 'localhost', 'dbname' => 'sqlando', 'user' => 'localUser'), 'mysql_createDB' => array('dbhost' => 'localhost', 'user' => 'localUser'))));
     // ## Register Official Silex Providers ##
     // Twig provider for templating
     // twig.path is /views and autoescape ought to be on
     $app->register(new \Silex\Provider\TwigServiceProvider(), array('twig.path' => 'views', 'twig.autoescape' => true));
     // session provider to handle user sessions
     $app->register(new \Silex\Provider\SessionServiceProvider());
     return $app;
 }
 /**
  * Creates the application.
  *
  * @return \Symfony\Component\HttpKernel\HttpKernel
  */
 public function createApplication()
 {
     $app = new Silex\Application();
     $app['foo'] = 'bar';
     $app->mount('/containerdoc', new ContainerDocProvider());
     return $app;
 }
 /**
  * Test Boot Finder
  *
  * @return void
  */
 public function testBootFinder()
 {
     $app = new Silex\Application();
     $app->register(new \NachoNerd\Silex\Finder\Provider());
     $app->boot();
     $this->assertInstanceOf('NachoNerd\\Silex\\Finder\\Extensions\\Finder', $app['nn.finder']);
 }
 /**
  * Test Register Finder
  *
  * @param integer $n Umpteenth Number
  *
  * @return void
  *
  * @dataProvider providerTestUmpteenth
  */
 public function testIntegratorSuccess($n)
 {
     $path = realpath(__DIR__ . "/../resources/") . "/";
     $oldFinder = new Symfony\Component\Finder\Finder();
     $app = new Silex\Application();
     $app->register(new \NachoNerd\Silex\Finder\Provider());
     $app->boot();
     $app['nn.finder']->sortByModifiedTimeDesc()->in($path);
     $newFinder = $app['nn.finder']->getNFirst($n);
     $filesNewWay = array();
     foreach ($newFinder as $files) {
         $filesNewWay[] = $files;
     }
     $oldFinder->sort(function ($a, $b) {
         return $b->getMTime() - $a->getMTime();
     })->in($path);
     $filesOldWay = array();
     $j = 0;
     foreach ($oldFinder as $files) {
         if ($j == $n) {
             break;
         }
         $j++;
         $filesOldWay[] = $files;
     }
     $this->assertEquals($filesOldWay, $filesNewWay);
 }
Example #5
0
 public function createApplication()
 {
     $app = new \Silex\Application();
     $app['debug'] = true;
     unset($app['exception_handler']);
     $app->register(new \Silex\Provider\TwigServiceProvider());
     return $app;
 }
function getApp()
{
    $app = new \Silex\Application();
    $app["debug"] = TRUE;
    $app->register(new ConsoleServiceProvider());
    $app->register(new DoctrineORMServiceProvider(), array("orm.connection" => array('driver' => "pdo_sqlite", 'path' => ROOT_TEST_DIR . '/database.sqlite'), "orm.driver.configs" => array("default" => array("namespace" => "Entity", "type" => "yaml", "paths" => array(ROOT_TEST_DIR . '/doctrine')))));
    return $app;
}
 static function getApp()
 {
     $app = new \Silex\Application();
     $app["debug"] = TRUE;
     $app["session.test"] = 1;
     $app->register(new ConsoleServiceProvider());
     $app->register(new DoctrineODMMongoDBServiceProvider(), array("odm.connection.server" => getenv('ODM_MONGODB_TEST_CONNECTION_STRING'), "odm.connection.dbname" => getenv('ODM_MONGODB_TEST_DATABASE_NAME'), "odm.connection.options" => array('connect' => TRUE), "odm.proxy_dir" => __DIR__ . "/Proxy", "odm.driver.configs" => array("default" => array("namespace" => "Entity", "path" => __DIR__ . "/Entity", "type" => "annotations"))));
     return $app;
 }
 function test()
 {
     $app = new \Silex\Application();
     $app->get('/foo', function () {
     })->bind('foo');
     $app->flush();
     $mock = $this->getMock('\\FrozenSilex\\Freezer', array('freezeRoute'), array($app));
     $mock->expects($this->once())->method('freezeRoute');
     $generator = new FreezingUrlGenerator(new UrlGenerator($app['routes'], $app['request_context']), $mock);
     $generator->generate('foo');
 }
 public function setUp()
 {
     vfsStreamWrapper::register();
     vfsStreamWrapper::setRoot(new vfsStreamDirectory('cacheDir'));
     $application = new \Silex\Application();
     $application[\Phruts\Util\Globals::DIGESTER] = $application->share(function () {
         $digester = new Digester();
         $digester->addRuleSet(new ConfigRuleSet('phruts-config'));
         return $digester;
     });
     $this->fileCache = new FileCacheModuleProvider($application);
     $this->fileCache->setCachePath(vfsStream::url('cacheDir'));
 }
 public function createApplication()
 {
     $app = new \Silex\Application();
     $app->register(new \Silex\Provider\FormServiceProvider());
     $app->register(new \Eccube\ServiceProvider\ValidatorServiceProvider());
     // fix php5.3
     $self = $this;
     $app['form.types'] = $app->share($app->extend('form.types', function ($types) use($app, $self) {
         $types[] = new \Eccube\Form\Type\RepeatedEmailType();
         return $types;
     }));
     return $app;
 }
Example #11
0
 public function createApplication()
 {
     // Silex
     $app = new Silex\Application();
     require __DIR__ . '/../../resources/config/test.php';
     require __DIR__ . '/../../src/app.php';
     // Use FilesystemSessionStorage to store session
     $app['session.storage'] = $app->share(function () {
         return new MockFileSessionStorage(sys_get_temp_dir());
     });
     // Controllers
     require __DIR__ . '/../../src/controllers.php';
     return $this->app = $app;
 }
 public function setUp()
 {
     parent::setUp();
     // \Eccube\Applicationは重いから呼ばない
     $app = new \Silex\Application();
     $app->register(new \Silex\Provider\FormServiceProvider());
     $app->register(new \Eccube\ServiceProvider\ValidatorServiceProvider());
     $self = $this;
     $app['form.types'] = $app->share($app->extend('form.types', function ($types) use($app, $self) {
         $types[] = new \Eccube\Form\Type\PriceType($self->config);
         return $types;
     }));
     // CSRF tokenを無効にしてFormを作成
     $this->form = $app['form.factory']->createBuilder('price', null, array('csrf_protection' => false))->getForm();
 }
 public function setUp()
 {
     parent::setUp();
     $app = new \Silex\Application();
     $app->register(new \Silex\Provider\FormServiceProvider());
     $app->register(new \Eccube\ServiceProvider\ValidatorServiceProvider());
     $app['form.types'] = $app->share($app->extend('form.types', function ($types) use($app) {
         $config['config']['name_len'] = 50;
         $types[] = new \Eccube\Form\Type\NameType($config['config']);
         // Nameに依存する
         return $types;
     }));
     // CSRF tokenを無効にしてFormを作成
     $this->form = $app['form.factory']->createBuilder('form', null, array('csrf_protection' => false))->add('name', 'name')->getForm();
 }
 /**
  * @inheritdoc
  * @param array $values
  */
 public function __construct(array $values = [])
 {
     $values['amazon_s3_client'] = $this->share(function (Application $app) {
         return S3Client::factory(array_merge($this->getCredentials(), ['version' => '2006-03-01', 'ssl.certificate_authority' => false]));
     });
     $values['amazon_s3_credentials_cookie_name'] = 'credentials';
     $values['controller.amazon_s3_client'] = $this->share(function (Application $app) {
         return new AmazonS3Controller($app['twig'], $app['amazon_s3_client']);
     });
     $values['controller.authentication'] = $this->share(function (Application $app) {
         return new AuthenticationController($app['twig'], $app['amazon_s3_credentials_cookie_name']);
     });
     parent::__construct($values);
     $this->register(new TwigServiceProvider(), ['twig.path' => __DIR__ . '/../views', 'twig.options' => ['cache' => is_writable(__DIR__ . '/..') ? __DIR__ . '/../cache/twig' : false]]);
     $this->register(new UrlGeneratorServiceProvider());
     $this->register(new ServiceControllerServiceProvider());
     $this->get('/login', 'controller.authentication:loginAction')->bind('login')->before(function (Request $request, Application $app) {
         $credentials = $this->getCredentials();
         if (!empty($credentials)) {
             return new RedirectResponse($app['url_generator']->generate('list'));
         }
     });
     $this->post('/login', 'controller.authentication:authenticateAction');
     $this->post('/logout', 'controller.authentication:logoutAction')->bind('logout');
     $this->get('/{bucket}', 'controller.amazon_s3_client:listAction')->value('bucket', null)->bind('list')->before(function (Request $request, Application $app) {
         $credentials = $this->getCredentials();
         if (empty($credentials)) {
             return $app->handle(Request::create($app['url_generator']->generate('login')), HttpKernelInterface::SUB_REQUEST, false);
         }
     });
 }
 /**
  * @param $template
  */
 public function render($template)
 {
     if (!$this->path) {
         $app = new \Silex\Application();
         $app->abort(500, "Path not defined!");
     }
     $file = $this->path . strtolower($template) . $this->extension;
     if (file_exists($file)) {
         $this->render = $file;
     } else {
         header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
         die('Template ' . $template . ' not found!');
     }
     $this->data['app'] = $this->app;
     extract($this->data);
     include $this->render;
 }
 public function createApplication()
 {
     // Silex
     $app = new Silex\Application();
     require __DIR__ . '/../../src/app.php';
     require __DIR__ . '/../../resources/config/dev.php';
     // Tests mode
     unset($app['exception_handler']);
     $app['translator.messages'] = array();
     // Use FilesystemSessionStorage to store session
     $app['session.storage'] = $app->share(function () {
         return new MockFileSessionStorage(sys_get_temp_dir());
     });
     // Controllers
     require __DIR__ . '/../../src/controllers.php';
     return $this->app = $app;
 }
 protected function createApplication($noTwig = false, $noSm = false)
 {
     $app = new \Silex\Application();
     $this->mockGenerator->orphanize('__construct');
     $sm = new \mock\Swift_Mailer();
     $this->calling($sm)->send = function ($message = null) {
         return $message;
     };
     $app->register(new \Rad\Silex\MailerServiceProvider(), array('rad_mailer.from' => '*****@*****.**'));
     if (!$noTwig) {
         $app->register(new \Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../../template'));
     }
     if (!$noSm) {
         $app['mailer'] = $sm;
     }
     $app->boot();
     return $app;
 }
Example #18
0
 public function runUpdate()
 {
     if (Capsule::schema()->hasTable('settings')) {
         $updateVersion = SettingModel::where('name', 'update_version')->first();
         if ($updateVersion && $updateVersion->value == $this->app['version']) {
             return $this->app->redirect('/');
         }
     }
     $s = new Seeder($this->app, $this->app['projects.creator']);
     $s->seedTemplates();
     $s->seedLibraries();
     if (SettingModel::where('name', 'update_version')->first()) {
         SettingModel::where('name', 'update_version')->update(array('value' => $this->app['version']));
     } else {
         SettingModel::insert(array('name' => 'update_version', 'value' => $this->app['version']));
     }
     return $this->app->redirect('/');
 }
Example #19
0
 /**
  * @return \Silex\Application
  */
 public static function bootstrap(array $config = array())
 {
     $config += array('root_dir' => __DIR__ . '/..');
     $config += array('conf_file' => $config['root_dir'] . '/conf/config.yml');
     $app = new \Silex\Application();
     // Registers the configuration service provider so that developers can
     // configure the app through a config file.
     $app->register(new \Igorw\Silex\ConfigServiceProvider($config['conf_file'], array('root_dir' => $config['root_dir'])));
     // Optionally add the monolog service provider if the "monolog.logfile"
     // configuration option is set.
     if (isset($app['monolog.logfile'])) {
         $app->register(new \Silex\Provider\MonologServiceProvider());
     }
     // Register the index and service manager as a service so we can query
     // our Acquia Search indexes.
     $app->register(new \Acquia\Search\Proxy\Silex\AcquiaSearchIndexProvider());
     // Dispatch the "acquia.search.proxy.bootstrap" event so that developers
     // can hook into the bootstrap process and add their providers.
     $event = new Event\AppEvent($app);
     $app['dispatcher']->dispatch(AppEvents::BOOTSTRAP, $event);
     return $app;
 }
 public function createApplication()
 {
     $app = new \Silex\Application(['debug' => true]);
     $app->register(new ParamConverterProvider());
     $app->register(new SessionServiceProvider(), ['session.test' => true]);
     $app->register(new SecurityServiceProvider(), ['security.firewalls' => ['unsecured' => ['anonymous' => true]]]);
     $app->register(new FormServiceProvider());
     return $app;
 }
 public function testCreateSilexApplication()
 {
     $logger = new \Psr\Log\NullLogger();
     $silex = new Silex\Application(array('debug' => true, 'logger' => $logger));
     $silex->register(new \PHPExtra\Proxy\Provider\Silex\ProxyServiceProvider(), array('logger' => $logger, 'proxy.storage' => new \PHPExtra\Proxy\Storage\InMemoryStorage(), 'proxy.adapter.name' => 'dummy', 'proxy.adapter.dummy.handler' => $silex->protect(function (\PHPExtra\Proxy\Http\RequestInterface $request) {
         return new \PHPExtra\Proxy\Http\Response('I see ' . $request->getRequestUri());
     }), 'proxy.logger.access_log' => $logger));
     $silex->register(new \PHPExtra\EventManager\Silex\EventManagerServiceProvider());
     $silex->boot();
     $request = \Symfony\Component\HttpFoundation\Request::create('http://test.com/ping');
     $response = $silex->handle($request);
     $silex->terminate($request, $response);
     $this->assertEquals('I see /ping', $response->getContent());
     $this->assertEquals(200, $response->getStatusCode());
 }
Example #22
0
<?php

require_once __DIR__ . '/../vendor/autoload.php';
function app_path($path = '/')
{
    $rootDir = realpath(__DIR__ . '/..') . '/';
    return preg_replace('/\\/+/', '/', $rootDir . $path);
}
$app = new Silex\Application();
$app['console'] = function () {
    return new \Symfony\Component\Console\Application();
};
if (file_exists(app_path('.env'))) {
    $dotenv = new \Dotenv\Dotenv(app_path());
    $dotenv->load();
}
$serviceProviderClasses = (require_once __DIR__ . '/providers.php');
foreach ($serviceProviderClasses as $serviceProviderClass) {
    $app->register(new $serviceProviderClass());
}
return $app;
Example #23
0
<?php

$app = new Silex\Application();
$app['debug'] = DEBUG;
Symfony\Component\Debug\ErrorHandler::register();
if ('cli' !== php_sapi_name()) {
    Symfony\Component\Debug\ExceptionHandler::register();
}
$app->register(new Silex\Provider\MonologServiceProvider(), array('monolog.logfile' => APP_DIR . '/../logs/app.error.log', 'monolog.level' => Monolog\Logger::ERROR));
$templateDir = APP_DIR . VIEWS_LOCATION;
$templatePaths = array($templateDir, $templateDir . '/templates', $templateDir . '/pages', $templateDir . '/error-pages');
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => $templatePaths, 'twig.options' => array('cache' => APP_DIR . 'cache')));
$app->register(new Silex\Provider\FormServiceProvider());
$app->register(new Silex\Provider\TranslationServiceProvider(), array('locale_fallbacks' => array('en')));
$app->register(new Silex\Provider\ValidatorServiceProvider());
$app->register(new Aws\Silex\AwsServiceProvider(), array('aws.config' => array('key' => AWS_USER_ACCESS_KEY, 'secret' => AWS_USER_SECRET_KEY, 'region' => 'eu-west-1')));
$app['twig']->addGlobal('publicAssetsLocation', PUBLIC_ASSETS_LOCATION);
Example #24
0
<?php

require_once __DIR__ . '/../vendor/autoload.php';
define('GOOGLE_API_KEY', '389361308386-0lc02qa6gs3q0pf7j86hhj169to93jh9.apps.googleusercontent.com');
define('GOOGLE_API_SECRET', 'nijEu5O05kXBLQv9pawzrF9Z');
$app = new Silex\Application();
error_reporting(E_ALL);
ini_set('display_errors', 1);
$app['debug'] = true;
$app->register(new Gigablah\Silex\OAuth\OAuthServiceProvider(), array('oauth.services' => array('Google' => array('key' => GOOGLE_API_KEY, 'secret' => GOOGLE_API_SECRET, 'scope' => array('https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'), 'user_endpoint' => 'https://www.googleapis.com/oauth2/v1/userinfo'))));
// Provides URL generation
$app->register(new Silex\Provider\UrlGeneratorServiceProvider());
// Provides CSRF token generation
$app->register(new Silex\Provider\FormServiceProvider());
// Provides session storage
$app->register(new Silex\Provider\SessionServiceProvider(), array('session.storage.save_path' => __DIR__ . '/../cache'));
// Provides Twig template engine
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__));
$app->register(new Silex\Provider\SecurityServiceProvider(), array('security.firewalls' => array('default' => array('pattern' => '^/', 'anonymous' => true, 'oauth' => array('failure_path' => '/', 'with_csrf' => true), 'logout' => array('logout_path' => '/logout', 'with_csrf' => true), 'users' => new Gigablah\Silex\OAuth\Security\User\Provider\OAuthInMemoryUserProvider())), 'security.access_rules' => array(array('^/auth', 'ROLE_USER'))));
$app->before(function (Symfony\Component\HttpFoundation\Request $request) use($app) {
    $token = $app['security']->getToken();
    $app['user'] = null;
    if ($token && !$app['security.trust_resolver']->isAnonymous($token)) {
        $app['user'] = $token->getUser();
    }
});
$app->get('/', function () use($app) {
    return $app['twig']->render('index.twig', array('login_paths' => $app['oauth.login_paths'], 'logout_path' => $app['url_generator']->generate('logout', array('_csrf_token' => $app['oauth.csrf_token']('logout')))));
});
$app->match('/logout', function () {
})->bind('logout');
Example #25
0
<?php

//ini_set("display_errors", true);
use Silex\Provider\ServiceControllerServiceProvider;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
require_once __DIR__ . "/../vendor/autoload.php";
$app = new Silex\Application();
require_once __DIR__ . "/../resources/config.php";
// Accept and decode JSON data before the call to controllers
$app->before(function (Request $request) {
    if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
        $data = json_decode($request->getContent(), true);
        $request->request->replace(is_array($data) ? $data : array());
    }
});
// Add correct headers before it is sent to the client
$app->after(function (Request $request, Response $response) {
    $response->headers->set("Access-Control-Allow-Origin", "*");
    $response->headers->set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
});
$app->register(new ServiceControllerServiceProvider());
$connection = new RestApp\Service\PDOConnection($app);
$app['todo.repo'] = $app->share(function () use($connection) {
    return new RestApp\Repository\TodoRepository($connection);
});
$app['todo.controller'] = $app->share(function () use($app) {
    return new RestApp\Controller\TodoController($app['todo.repo']);
});
$app['converter.user'] = $app->share(function () use($app) {
Example #26
0
<?php

require '../vendor/autoload.php';
$app = new Silex\Application();
$app['debug'] = true;
// Register the monolog logging service
$app->register(new Silex\Provider\MonologServiceProvider(), array('monolog.logfile' => 'php://stderr'));
// Register view rendering
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/views'));
// Our web handlers
$app->get('/', function () use($app) {
    $app['monolog']->addDebug('logging output.');
    return $app['twig']->render('index.twig');
});
$app->get('/page2', function () use($app) {
    $app['monolog']->addDebug('logging output.');
    return $app['twig']->render('page2.twig');
});
$app->run();
Example #27
0
<?php

require_once __DIR__ . "/../vendor/autoload.php";
require_once __DIR__ . "/../src/car.php";
$app = new Silex\Application();
$app->get("/", function () {
    return "\n        <!DOCTYPE html>\n        <html>\n        <head>\n          <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css'>\n          <title>CARS!</title>\n        </head>\n        <body>\n            <div class='container'>\n                <h1>Enter Max Mileage and Max Price</h1>\n                <form action='/view_cars'>\n                    <div class='form-group'>\n                        <label for='max_mileage'>Maximum Mileage:</label>\n                        <input id='max_mileage' name='max_mileage' class='form-control' type='number'>\n                    </div>\n                    <div class='form-group'>\n                        <label for='max_price'>Maximum Price:</label>\n                        <input id='max_price' name='max_price' class='form-control' type='number'>\n                    </div>\n                    <button type='submit' class='btn'>Go!</button>\n                </form>\n            </div>\n        </body>\n        </html>";
});
$app->get("/view_cars", function () {
    $firstCar = new Car("Tesla X", 100000, 0, "pictures/tesla.jpg");
    $secondCar = new Car("Honda Accord", 10000, 50000, "pictures/honda.jpg");
    $thirdCar = new Car("Ferrari Enzo", 350000, 15000, "pictures/ferrari-enzo.jpg");
    $fourthCar = new Car("Toyota Corolla", 6000, 100000, "pictures/toyota-corolla.jpg");
    $fifthCar = new Car("Mitsubishi Lancer", 20000, 100, "pictures/mitsubishi-lancer.jpg");
    $allCars = array($firstCar, $secondCar, $thirdCar, $fourthCar, $fifthCar);
    function searchCar($maxPrice, $maxMileage, $cars)
    {
        $searchedCars = array();
        foreach ($cars as $car) {
            $price = $car->getPrice();
            $mileage = $car->getMiles();
            if ($price <= $maxPrice && $mileage <= $maxMileage) {
                array_push($searchedCars, $car);
            }
        }
        return $searchedCars;
    }
    $matchingCars = searchCar($_GET["max_price"], $_GET["max_mileage"], $allCars);
    $output = '';
    $output .= '<h1>Available Cars</h1>' . "\n ";
    if (empty($matchingCars)) {
Example #28
0
<?php

/**
 * simple web app that returns info on a subnet through a JSON api
 *
 * @licence GPLv3
 * @author Lucas Bickel <*****@*****.**>
 */
require_once __DIR__ . '/../vendor/autoload.php';
$app = new Silex\Application();
#$app['debug'] = true;
$app['cache_ttl'] = 86400;
$app->register(new Silex\Provider\RoutingServiceProvider());
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../app/views'));
$app->register(new Silex\Provider\HttpCacheServiceProvider(), array('http_cache.cache_dir' => __DIR__ . '/../app/cache/', 'http_cache.options' => ['default_ttl' => $app['cache_ttl']]));
$app->get('/', function () use($app) {
    return $app['twig']->render('index.html.twig');
})->bind('home');
$app->get('/swagger.json', function () use($app) {
    return new Symfony\Component\HttpFoundation\Response($app['twig']->render('swagger.json.twig'), 200, ['Content-Type' => 'application/json']);
})->bind('swagger');
$app->get('/apis.json', function () use($app) {
    return new Symfony\Component\HttpFoundation\Response($app['twig']->render('apis.json.twig'), 200, ['Content-Type' => 'application/json']);
})->bind('apisjson');
$app->get('/subnet/{ip}/{mask}', function ($ip, $mask) use($app) {
    $subnet = $ip . '/' . $mask;
    try {
        $subnet_info = IPTools\Network::parse($subnet)->info;
        unset($subnet_info['class']);
    } catch (Exception $e) {
        $app->abort(400, $e->getMessage());
Example #29
0
<?php

define('DB_HOST', 'localhost');
define('DB_NAME', 'exercice-silex-zrihen-petit');
define('DB_USER', 'root');
define('DB_PASS', 'root');
try {
    $pdo = new PDO('mysql:dbname=' . DB_NAME . ';host=' . DB_HOST, DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_NAMED);
} catch (PDOException $e) {
    die('error');
}
require_once __DIR__ . '/../vendor/autoload.php';
$app = new Silex\Application();
$app['debug'] = true;
// Twig
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/views'));
// Url Generator
$app->register(new Silex\Provider\UrlGeneratorServiceProvider());
include 'models/snippets.class.php';
$snippets_model = new Snippets_Model($pdo);
Example #30
0
<?php

require_once __DIR__ . "/../vendor/autoload.php";
require_once __DIR__ . "/../src/Task.php";
require_once __DIR__ . "/../src/Category.php";
//session_start();
//if (empty($_SESSION['list_of_tasks'])) {
//    $_SESSION['list_of_tasks'] = array();
//}
$app = new Silex\Application();
$server = 'mysql:host=localhost;dbname=to_do';
$username = '******';
$password = '******';
$DB = new PDO($server, $username, $password);
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../views'));
$app->get("/", function () use($app) {
    return $app['twig']->render('index.html.twig');
});
$app->get("/tasks", function () use($app) {
    return $app['twig']->render('tasks.html.twig', array('tasks' => Task::getAll()));
});
$app->get("/categories", function () use($app) {
    return $app['twig']->render('categories.html.twig', array('categories' => Category::getAll()));
});
$app->post("/tasks", function () use($app) {
    $task = new task($_POST['description']);
    $task->save();
    return $app['twig']->render('tasks.html.twig', array('tasks' => Task::getAll()));
});
$app->post("/delete_tasks", function () use($app) {
    Task::deleteAll();