예제 #1
0
 public function getAppWithMockCli($mockContent = null)
 {
     $app = new Pimple\Container();
     $app->register(new Wpbootstrap\Providers\DefaultObjectProvider());
     $app['cli'] = new MockCliWrapper($mockContent);
     $app['cliutils'] = new MockCliUtilsWrapper();
     $app->register(new Wpbootstrap\Providers\ApplicationParametersProvider());
     return $app;
 }
예제 #2
0
 /**
  * Constructor.
  *
  * @param \Pimple|\Pimple\Container|null $container
  */
 public function __construct($container = null)
 {
     if ($container === null) {
         if (class_exists('Pimple\\Container')) {
             $container = new \Pimple\Container();
             $container->register(new BeanstalkPimple3ServiceProvider());
         } else {
             $container = new \Pimple();
             $sp = new BeanstalkPimple1ServiceProvider();
             $sp->register($container);
         }
     }
     $container['beanstalk.console_commands.queue_prefix'] = '';
     parent::__construct('Queue', null, $container);
     $this->addCommands($container['beanstalk.console_commands']);
 }
예제 #3
0
 /**
  * Constructor
  *
  * @param string $version
  * @param string $file
  */
 public function __construct($version, $file)
 {
     // set version
     $this->version = $version;
     // Pimple Container construct
     parent::__construct();
     // register file service
     $this['file'] = function () use($file) {
         return new File($file);
     };
     // register services early since some add-ons need 'm
     $this->register_services();
     // this complete plugin is pretty much admin only
     if (is_admin()) {
         // alias for Pimple container
         $c = $this;
         // enqueue CSS
         add_action('admin_enqueue_scripts', function () use($c) {
             wp_enqueue_style('wpcm_admin', $c['file']->plugin_url('/assets/css/wp-notification-center.css'), array(), $c->get_version());
         });
         // catch admin notices
         $this['admin_notice_handler']->catch_admin_notices();
         // setup admin bar
         $admin_bar = new AdminBar();
         $admin_bar->setup();
         // setup plugin links
         $plugin_links = new PluginLinks();
         $plugin_links->setup();
     }
 }
 public function testFactory()
 {
     $url = 'http://localhost:8983/solr/';
     $user = "******";
     $pass = "******";
     $timeout = 13;
     $options = ['timeout' => $timeout];
     $container = new \Pimple\Container();
     $provider = SolrClientServiceProvider::factory($url, $user, $pass, $options);
     $container->register($provider);
     $client = $container['solr'];
     $this->assertInstanceOf(Client::class, $client);
     $guzzle = $client->getGuzzleClient();
     $this->assertSame($url, (string) $guzzle->getConfig('base_uri'));
     $this->assertSame([$user, $pass], $guzzle->getConfig('auth'));
     $this->assertSame($timeout, $guzzle->getConfig('timeout'));
 }
예제 #5
0
 /**
  * Constructor
  *
  * @param string $version
  * @param string $file
  */
 public function __construct($version, $file)
 {
     // set version
     $this->version = $version;
     // Pimple Container construct
     parent::__construct();
     // setup custom database tables
     $this->setup_db_tables();
     // register file service
     $this['file'] = function () use($file) {
         return new File($file);
     };
     // register services early since some add-ons need 'm
     $this->register_services();
     // load the plugin
     $this->load();
 }
예제 #6
0
파일: common.php 프로젝트: Folcky/kanboard
<?php

require dirname(__DIR__) . '/vendor/autoload.php';
// Automatically parse environment configuration (Heroku)
if (getenv('DATABASE_URL')) {
    $dbopts = parse_url(getenv('DATABASE_URL'));
    define('DB_DRIVER', $dbopts['scheme']);
    define('DB_USERNAME', $dbopts["user"]);
    define('DB_PASSWORD', $dbopts["pass"]);
    define('DB_HOSTNAME', $dbopts["host"]);
    define('DB_PORT', isset($dbopts["port"]) ? $dbopts["port"] : null);
    define('DB_NAME', ltrim($dbopts["path"], '/'));
}
// Include custom config file
if (file_exists('config.php')) {
    require 'config.php';
}
require __DIR__ . '/constants.php';
require __DIR__ . '/check_setup.php';
$container = new Pimple\Container();
$container->register(new Kanboard\ServiceProvider\SessionProvider());
$container->register(new Kanboard\ServiceProvider\LoggingProvider());
$container->register(new Kanboard\ServiceProvider\DatabaseProvider());
$container->register(new Kanboard\ServiceProvider\ClassProvider());
$container->register(new Kanboard\ServiceProvider\EventDispatcherProvider());
if (ENABLE_URL_REWRITE) {
    require __DIR__ . '/routes.php';
}
$container['pluginLoader']->scan();
 /**
  * getMultipleConnectionsContainer
  *
  * @return \Pimple\Container
  */
 protected function getMultipleConnectionsContainer()
 {
     $container = new \Pimple\Container();
     $container['amqp.options'] = ['connections' => ['conn1' => array('host' => '127.0.0.1', 'port' => 5672, 'login' => 'guest', 'password' => 'guest', 'vhost' => '/'), 'conn2' => array('host' => '127.0.0.1', 'port' => 5672, 'login' => 'guest', 'password' => 'guest', 'vhost' => '/')]];
     $container->register(new AMQPServiceProvider());
     return $container;
 }
<?php

$container = new \Pimple\Container();
$container['a'] = $container->factory(function ($c) {
    return new A();
});
$container['b'] = $container->factory(function ($c) {
    return new B($c['a']);
});
$container['c'] = $container->factory(function ($c) {
    return new C($c['b']);
});
$container['d'] = $container->factory(function ($c) {
    return new D($c['c']);
});
$container['e'] = $container->factory(function ($c) {
    return new E($c['d']);
});
$container['f'] = $container->factory(function ($c) {
    return new F($c['e']);
});
$container['g'] = $container->factory(function ($c) {
    return new G($c['f']);
});
$container['h'] = $container->factory(function ($c) {
    return new H($c['g']);
});
$container['i'] = $container->factory(function ($c) {
    return new I($c['h']);
});
$container['j'] = $container->factory(function ($c) {
예제 #9
0
<?php

/**
 * Created by PhpStorm.
 * User: Rusinov
 * Date: 28.06.15
 * Time: 13:42
 */
require 'autoload.php';
require 'vendor/autoload.php';
$container = new \Pimple\Container();
$container['config'] = function () {
    return new \Core\Config();
};
$container['DB'] = function ($c) {
    return new \Core\DB($c['config']['server_name'], $c['config']['db_user'], $c['config']['db_pass'], $c['config']['db_name']);
};
$container['StreamSaverWorker'] = $container->factory(function ($c) {
    return new \StreamSaver\Worker($c['config']['stream_url'], $c['config']['video_length'], $c['config']['video_format'], $c['config']['project_root'] . $c['config']['video_dir'], $c['DB']);
});
// Реальный соап-клиент
//$container['ScheduleSoapClient'] = function ($c) {
//	return new SoapClient(
//		$c['config']['schedule_wsdl_url']
//	);
//};
// Стаб соап-клиента
$container['ScheduleSoapClient'] = function ($c) {
    return new \Schedule\MySoapClient($c['config']['schedule_wsdl_url']);
};
$container['SoapScheduleProvider'] = function ($c) {
예제 #10
0
<?php

require 'vendor/autoload.php';
// Include custom config file
if (file_exists('config.php')) {
    require 'config.php';
}
require __DIR__ . '/constants.php';
$container = new Pimple\Container();
$container->register(new ServiceProvider\Logging());
$container->register(new ServiceProvider\Database());
$container->register(new ServiceProvider\Event());
$container->register(new ServiceProvider\Mailer());
<?php

$t1 = microtime(true);
$container = new \Pimple\Container();
$container['a'] = $container->factory(function ($c) {
    return new A();
});
for ($i = 0; $i < 10000; $i++) {
    $j = $container['a'];
}
$t2 = microtime(true);
$results = ['time' => $t2 - $t1, 'files' => count(get_included_files()), 'memory' => memory_get_peak_usage() / 1024 / 1024];
echo json_encode($results);
예제 #12
0
 * Version: 0.1
 * Author: Tom Forrer
 * Author URI: http://githubm.com/tmf
 * License: MIT
 */
/**
 * @autor     Tom Forrer <*****@*****.**>
 * @copyright Copyright (c) 2014 Tom Forrer (http://github.com/tmf)
 */
if (!file_exists(__DIR__ . '/base')) {
    symlink(__DIR__ . '/../../../..', __DIR__ . '/base');
}
if (file_exists(__DIR__ . '/base/vendor/autoload.php')) {
    require_once __DIR__ . '/base/vendor/autoload.php';
}
use Tmf\Wordpress\Service\Metabox\MetaboxServiceProvider, Tmf\Wordpress\Service\Metabox\Metabox, Tmf\Wordpress\Service\Metabox\Item\InputItem, Tmf\Wordpress\Service\Metabox\Item\DropdownItem, Tmf\Wordpress\Service\Metabox\Item\EditorItem, Tmf\Wordpress\Service\Metabox\Item\PostsDropdownItem, Tmf\Wordpress\Service\Metabox\Item\DateTimeItem;
$services = new Pimple\Container();
// $plugin contains the path of this plugin as wordpress sees it
$services->register(new MetaboxServiceProvider(), ['metaboxes.base_directory' => dirname($plugin) . '/base', 'metaboxes.vendor_directory' => dirname($plugin) . '/base/vendor']);
add_action('admin_init', function () use($services) {
    $services['metaboxes']['foo'] = new Metabox('Foo', ['post'], 'normal', 'high');
    $services['metaboxes']['foo']['text'] = new InputItem(['label' => 'Metatext', 'description' => 'Some description']);
    $services['metaboxes']['foo']['dropdown'] = new DropdownItem(['multiple' => false, 'label' => 'Dropdown', 'options' => [['label' => 'Foo', 'value' => 'foo'], ['label' => 'ASDF', 'value' => 'asdf']]]);
    $services['metaboxes']['foo']['editor'] = new EditorItem(['label' => 'Editor']);
    $services['metaboxes']['foo']['some_posts'] = new PostsDropdownItem(['label' => 'Some posts', 'options' => function () {
        return array_map(function (WP_Post $post) {
            return ['label' => $post->post_title, 'value' => $post->ID, 'data' => ['data' => htmlentities(json_encode($post))]];
        }, get_posts(['posts_per_page' => -1]));
    }]);
    $services['metaboxes']['foo']['date'] = new DateTimeItem(['label' => 'Some Date', 'config' => ['timepicker' => false, 'format' => 'd.m.Y']]);
});
예제 #13
0
파일: app.php 프로젝트: mattjmattj/maybe
<?php

namespace Maybe\Examples\Log;

require __DIR__ . '/../../vendor/autoload.php';
use Maybe\Maybe;
/*
 * Actor wants an instance of Log to log what it does. But if we don't care, or
 * if we don't know if an actual instance of Log is available, we can wrap Log 
 * with Maybe and be safe without having to change anything in Actor.
 *
 * In this example we pretend to have a Pimple container providing both Log and
 * Actor, but we don't actually have a Log instance
 */
$container = new \Pimple\Container();
$container['Actor'] = $container->factory(function ($c) {
    return new Actor($c['Log']);
});
//we have no actual Log
$container['__Log'] = null;
// MaybeLog wraps Log
$container['MaybeLog'] = function ($c) {
    return new Maybe('Maybe\\Examples\\Log\\Log');
};
// and we define a factory to wrap actual instances of Log, if any, using MaybeLog
$container['Log'] = $container->factory(function ($c) {
    return $c['MaybeLog']->wrap($c['__Log']);
});
$actor = $container['Actor'];
$actor->doSomething();
// doSomething worked fine without logging anything
예제 #14
0
 private static function configure()
 {
     $container = new \Pimple\Container(array(DataFeed::FEED_STORE => function ($c) {
         global $wpdb;
         return new \DataFeed\Store\DatabaseFeedStore($wpdb, $c[DataFeed::FEED_HANDLE_FACTORY]);
     }, DataFeed::FEED_CACHE_BACKEND => function ($c) {
         if (function_exists('\\curl_init')) {
             return new \DataFeed\Cache\CurlFeedCache();
         }
         return new \DataFeed\Cache\FileGetContentsFeedCache();
     }, DataFeed::FEED_CACHE => function ($c) {
         return new \DataFeed\Cache\TransientFeedCache($c[DataFeed::FEED_CACHE_BACKEND], $c[DataFeed::TRANSIENT_CACHE]);
     }, DataFeed::FEED_HANDLE_FACTORY => function ($c) {
         return new \DataFeed\Internal\DefaultFeedHandleFactory($c[DataFeed::FEED_CACHE], $c[DataFeed::PAGE_URL_FACTORY], $c[DataFeed::PAGE_UPDATE_CHECK_FACTORY]);
     }, DataFeed::OBJECT_QUERY_LANGUAGE => function ($c) {
         return new \DataFeed\ObjectQuery\SimpleObjectQueryLanguage();
     }, DataFeed::REST_SERVICE => function ($c) {
         return new \DataFeed\Ajax\DefaultRestService($c[DataFeed::FEED_HANDLE_FACTORY], $c[DataFeed::FEED_CACHE], $c[DataFeed::REQUEST_DATA_FETCHER]);
     }, DataFeed::REQUEST_DATA_FETCHER => function ($c) {
         return new \DataFeed\Ajax\DefaultRequestDataFetcher();
     }, DataFeed::OBJECT_CACHE => function ($c) {
         return new \DataFeed\Cache\ObjectCache();
     }, DataFeed::TRANSIENT_CACHE => function ($c) {
         return new \DataFeed\Cache\TransientCache();
     }, DataFeed::PAGE_UPDATE_CHECK_FACTORY => function ($c) {
         return new \DataFeed\Pagination\PageUpdateCheckFactory();
     }, DataFeed::PAGE_URL_FACTORY => function ($c) {
         return new \DataFeed\Pagination\PageUrlFactory($c[DataFeed::OBJECT_QUERY_LANGUAGE]);
     }, DataFeed::OBJECT_MERGER => function ($c) {
         return new \DataFeed\ObjectMerge\DefaultObjectMerge();
     }));
     $container[self::FEED_HANDLE_FACTORY]->setFeedStore($container[self::FEED_STORE]);
     $container[self::MERGING_FEED_CACHE] = $container->factory(function ($c) {
         return new \DataFeed\Cache\MergingFeedCache($c[DataFeed::FEED_CACHE], $c[DataFeed::OBJECT_CACHE], $c[DataFeed::OBJECT_MERGER]);
     });
     self::$container = $container;
 }
예제 #15
0
<?php

require_once "../vendor/autoload.php";
$container = new Pimple\Container();
$container["service.request"] = $container->factory(function (Pimple\Container $c) {
    $request = new SlaxWeb\Router\Request();
    if ($c["router.protocol"] === "cli") {
        $request->setUpCLI($c["router.uri"]);
    }
    return $request;
});
$container["service.router"] = $container->factory(function (Pimple\Container $c) {
    $request = $c["service.request"];
    $router = new SlaxWeb\Router\Router($request);
    SlaxWeb\Router\Helper::init($router, $request);
    return $router;
});
$options = getopt("u:", ["uri:"]);
if (isset($options["u"])) {
    $options["uri"] = $options["u"];
}
$container["router.protocol"] = "cli";
$container["router.uri"] = $options["uri"];
$router = $container["service.router"];
require_once "../app/routes.php";
$action = $router->process();
$container["app.action"] = $action["action"];
$container["app.params"] = $action["params"];
$container["app.action"];
<?php

$container = new \Pimple\Container();
$container['a'] = function ($c) {
    return new A();
};
$container['b'] = $container->factory(function ($c) {
    return new B($c['a']);
});
//trigger autoloader
$b = $container['b'];
unset($b);
$t1 = microtime(true);
for ($i = 0; $i < 10000; $i++) {
    $j = $container['b'];
}
$t2 = microtime(true);
$results = ['time' => $t2 - $t1, 'files' => count(get_included_files()), 'memory' => memory_get_peak_usage() / 1024 / 1024];
echo json_encode($results);
예제 #17
0
파일: di.php 프로젝트: matheusd/resourceful
 public function register(Pimple\Container $c)
 {
     include __DIR__ . '/../local/config.php';
     foreach ($env as $envk => $envval) {
         $c["config/{$envk}"] = $envval;
     }
     $c['routes'] = ['/' => 'route/index', '/test', '/index', '/form', '/exception'];
     $c['entityManager'] = function ($c) {
         $config = Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration(array(__DIR__ . "/orm"), $c['config/devVersion']);
         $conn = $c['config/databases']['default'];
         return Doctrine\ORM\EntityManager::create($conn, $config);
     };
     $c['dispatcher'] = function ($c) {
         $routes = $c['routes'];
         $dispatcher = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) use($routes) {
             foreach ($routes as $k => $v) {
                 if (is_int($k)) {
                     $k = $v;
                     $v = "route{$v}";
                 }
                 $r->addRoute('*', $k, $v);
             }
         });
         return $dispatcher;
     };
     $c['request'] = function ($c) {
         $req = Zend\Diactoros\ServerRequestFactory::fromGlobals($_SERVER, $_GET, $_POST, $_COOKIE, $_FILES);
         $c['logger']->notice('Started ' . $req->getMethod() . ' ' . $req->getUri()->getPath());
         return $req;
     };
     $c['resource'] = function ($c) {
         $dispatcher = $c['dispatcher'];
         $request = $c['request'];
         $uri = $request->getUri();
         $path = $uri->getPath();
         if (preg_match("|^(.+)\\..+\$|", $path, $matches)) {
             //if path ends in .json, .html, etc, ignore it
             $path = $matches[1];
         }
         $res = $dispatcher->dispatch('*', $path);
         if ($res[0] == FastRoute\Dispatcher::NOT_FOUND) {
             throw new WebAppRouteNotFoundException("Route '{$path}' not found on routing table");
         }
         $reqParameters = $res[2];
         $c['requestParameters'] = $reqParameters;
         $entry = $res[1];
         if (!isset($c[$entry])) {
             throw new WebAppResourceNotFoundException("Resource '{$entry}' not found on DI container");
         }
         $res = $c[$entry];
         $c['logger']->notice("Resource Selected ({$entry}): " . get_class($res));
         return $res;
     };
     $c['response'] = function ($c) {
         try {
             $resource = $c['resource'];
             return $resource->exec();
         } catch (Exception $e) {
             return $c['handleException']($e);
         }
     };
     $c['templaterFactory'] = function ($c) {
         $temp = new ExampleApp\templater\SampleTemplaterFactory();
         $temp->globalContext = ['url' => $c['config/publicUrl'], 'assetsUrl' => $c['config/assetsUrl']];
         return $temp;
     };
     $c['responseFactory'] = function ($c) {
         $respFactory = new Resourceful\ResponseFactory();
         $respFactory->templaterFactory = $c['templaterFactory'];
         return $respFactory;
     };
     $c['responseEmitter'] = function ($c) {
         return new Zend\Diactoros\Response\SapiEmitter();
     };
     $c['session'] = function ($c) {
         $sess = new Resourceful\SessionStorage("ExampleApp");
         $sess->startSession();
         return $sess;
     };
     $c['logger'] = function ($c) {
         $handler = new Monolog\Handler\ErrorLogHandler(Monolog\Handler\ErrorLogHandler::SAPI, Monolog\Logger::NOTICE);
         $formatter = new Monolog\Formatter\LineFormatter();
         $formatter->includeStacktraces(true);
         $handler->setFormatter($formatter);
         $log = new Monolog\Logger('webapp');
         $log->pushHandler($handler);
         return $log;
     };
     $c['handleException'] = $c->protect(function ($e) use($c) {
         $c['logger']->error($e);
         $exceptionBuilder = new \Resourceful\Exception\ExceptionResponseBuilder();
         $exceptionBuilder->includeStackTrace = $c['config/devVersion'];
         $exceptionBuilder->responseFactory = $c['responseFactory'];
         $request = null;
         try {
             $request = $c['request'];
         } catch (Exception $e) {
             //ignore and just use a null request
         }
         $resp = $exceptionBuilder->buildResponse($e, $request);
         return $resp;
     });
     $mkres = function ($cls) use($c) {
         return function ($c) use($cls) {
             $res = new $cls();
             $res->request = $c['request'];
             $res->parameters = $c['requestParameters'];
             $res->responseFactory = $c['responseFactory'];
             $res->session = $c['session'];
             return $res;
         };
     };
     $c['route/index'] = $mkres('ExampleApp\\Home\\Control\\IndexResource');
     $c['route/form'] = $mkres('ExampleApp\\Home\\Control\\FormResource');
     $c['route/exception'] = $mkres('ExampleApp\\Home\\Control\\ExceptionResource');
 }
예제 #18
0
 /**
  * Instantiates framework and plugin modules
  *
  * Kind of like an app container
  *
  * @param  string  $module   The module to load
  * @param  array   $args     Constructor arguments
  * @param  boolean $isGlobal If the module is part of the framework
  * @return object            An instance of the module
  */
 public function make($module)
 {
     $instance = $this->container->make($module);
     return $instance;
 }
예제 #19
0
파일: common.php 프로젝트: perburn/kanboard
// Automatically parse environment configuration (Heroku)
if (getenv('DATABASE_URL')) {
    $dbopts = parse_url(getenv('DATABASE_URL'));
    define('DB_DRIVER', $dbopts['scheme']);
    define('DB_USERNAME', $dbopts["user"]);
    define('DB_PASSWORD', $dbopts["pass"]);
    define('DB_HOSTNAME', $dbopts["host"]);
    define('DB_PORT', isset($dbopts["port"]) ? $dbopts["port"] : null);
    define('DB_NAME', ltrim($dbopts["path"], '/'));
}
if (file_exists('config.php')) {
    require 'config.php';
}
if (file_exists('data' . DIRECTORY_SEPARATOR . 'config.php')) {
    require 'data' . DIRECTORY_SEPARATOR . 'config.php';
}
require __DIR__ . '/constants.php';
require __DIR__ . '/check_setup.php';
$container = new Pimple\Container();
$container->register(new Kanboard\ServiceProvider\SessionProvider());
$container->register(new Kanboard\ServiceProvider\LoggingProvider());
$container->register(new Kanboard\ServiceProvider\DatabaseProvider());
$container->register(new Kanboard\ServiceProvider\AuthenticationProvider());
$container->register(new Kanboard\ServiceProvider\NotificationProvider());
$container->register(new Kanboard\ServiceProvider\ClassProvider());
$container->register(new Kanboard\ServiceProvider\EventDispatcherProvider());
$container->register(new Kanboard\ServiceProvider\GroupProvider());
$container->register(new Kanboard\ServiceProvider\RouteProvider());
$container->register(new Kanboard\ServiceProvider\ActionProvider());
$container->register(new Kanboard\ServiceProvider\ExternalLinkProvider());
$container->register(new Kanboard\ServiceProvider\PluginProvider());
예제 #20
0
파일: index.php 프로젝트: vitrig/si
<?php

include __DIR__ . '/vendor/autoload.php';
$app = new Pimple\Container();
foreach (include __DIR__ . '/app/config.php' as $option => $value) {
    $app[$option] = $value;
}
$app['db'] = function () use($app) {
    $pdo = new PDO("mysql:host=" . $app["db.host"] . ";dbname=" . $app["db.name"], $app["db.user"], $app["db.pass"], [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"]);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $pdo;
};
$app['validate_name'] = $app->protect(function ($name) {
    return 1 == preg_match("/^[a-zA-ZłśćńóźżęąŁŚĆŃÓŻŹĘĄ-]+\$/", $name);
});
$app['validate_worker'] = $app->protect(function (&$entry) use($app) {
    $errors = array();
    $validate_name = $app['validate_name'];
    if (empty($entry["name"])) {
        $errors["name"] = "Imie nie może być puste";
    } else {
        if (!$validate_name($entry["name"])) {
            $errors["name"] = "Musisz podać poprawne imie";
            $entry["name"] = NULL;
        }
    }
    if (empty($entry["last_name"])) {
        $errors["last_name"] = "Nazwisko nie może być puste";
    } else {
        if (!$validate_name($entry["last_name"])) {
            $errors["last_name"] = "Musisz podać poprawne nazwisko";
예제 #21
0
    define('DB_PASSWORD', $dbSettings['password']);
    define('DB_HOSTNAME', $dbSettings['hostname']);
    define('DB_PORT', $dbSettings['port']);
    define('DB_NAME', $dbSettings['database']);
}
$config_file = implode(DIRECTORY_SEPARATOR, array(__DIR__, '..', 'config.php'));
if (file_exists($config_file)) {
    require $config_file;
}
$config_file = implode(DIRECTORY_SEPARATOR, array(__DIR__, '..', 'data', 'config.php'));
if (file_exists($config_file)) {
    require $config_file;
}
require __DIR__ . '/constants.php';
require __DIR__ . '/check_setup.php';
$container = new Pimple\Container();
$container->register(new Kanboard\ServiceProvider\MailProvider());
$container->register(new Kanboard\ServiceProvider\HelperProvider());
$container->register(new Kanboard\ServiceProvider\SessionProvider());
$container->register(new Kanboard\ServiceProvider\LoggingProvider());
$container->register(new Kanboard\ServiceProvider\DatabaseProvider());
$container->register(new Kanboard\ServiceProvider\AuthenticationProvider());
$container->register(new Kanboard\ServiceProvider\NotificationProvider());
$container->register(new Kanboard\ServiceProvider\ClassProvider());
$container->register(new Kanboard\ServiceProvider\EventDispatcherProvider());
$container->register(new Kanboard\ServiceProvider\GroupProvider());
$container->register(new Kanboard\ServiceProvider\RouteProvider());
$container->register(new Kanboard\ServiceProvider\ActionProvider());
$container->register(new Kanboard\ServiceProvider\ExternalLinkProvider());
$container->register(new Kanboard\ServiceProvider\AvatarProvider());
$container->register(new Kanboard\ServiceProvider\FilterProvider());
예제 #22
0
 /**
  * @param Pimple\Container $pimple
  */
 function it_adds_parameters_on_pimple($pimple, $loader)
 {
     $pimple->offsetSet('hello', 'world')->shouldBeCalled();
     $loader->load('config.json')->willReturn(array('hello' => 'world'));
     $this->configure($pimple, 'config.json');
 }
예제 #23
0
 public function __construct()
 {
     if (basename(__DIR__) !== __NAMESPACE__) {
         throw new \LogicException(sprintf('%s: `%s` is an invalid framework filesystem directory! Must be `%s`.', __CLASS__, basename(__DIR__), __NAMESPACE__), 1322213425);
     }
     $this->registerNamespace(__DIR__);
     $this->urlParts = $this->guessUrlParts();
     $nsMap =& $this->namespaceMap;
     $urlParts =& $this->urlParts;
     $dc = new \Pimple\Container();
     $dc['main.default_module'] = '';
     $dc['login.forced_redirect'] = '';
     $dc['decorator.xhtml.template'] = 'Nethgui\\Template\\Main';
     $dc['user.authenticate'] = $dc->protect(function ($user, $password, &$credentials) use($dc) {
         $dc['Log']->warning(sprintf("%s: user.authenticate is not set! Could not authenticate user `%s`.", __CLASS__, $user));
         return FALSE;
     });
     $dc['l10n.available_languages'] = function ($c) {
         $langs = array();
         foreach ($c['namespaceMap'] as $ns => $prefix) {
             $path = "{$prefix}/{$ns}/Language/*";
             $langs = array_unique(array_merge($langs, array_map('basename', $c['PhpWrapper']->glob($path, GLOB_ONLYDIR))));
         }
         return $langs;
     };
     $dc['l10n.preferred_locales'] = array('en');
     $dc['l10n.catalog_resolver'] = $dc->protect(function ($lang, $catalog) use($dc) {
         $languages = array_merge(array($lang), $dc['l10n.preferred_locales']);
         foreach ($languages as $lang) {
             foreach ($dc['namespaceMap'] as $ns => $prefix) {
                 $path = "{$prefix}/{$ns}/Language/{$lang}/{$catalog}.php";
                 if ($dc['PhpWrapper']->file_exists($path)) {
                     return $path;
                 }
             }
         }
         return '';
     });
     $dc['Log'] = function ($c) {
         return new \Nethgui\Log\Syslog($c['log.level']);
     };
     $dc['PhpWrapper'] = function ($c) {
         $p = new \Nethgui\Utility\PhpWrapper();
         $p->setLog($c['Log']);
         return $p;
     };
     $dc['namespaceMap'] = function ($c) use(&$nsMap) {
         return $nsMap;
     };
     $dc['Session'] = function ($c) {
         $s = new \Nethgui\Utility\Session();
         $s->setLog($c['Log']);
         return $s;
     };
     $dc['Pdp'] = function ($c) {
         $pdp = new \Nethgui\Authorization\JsonPolicyDecisionPoint($c['FilenameResolver']);
         $pdp->setLog($c['Log']);
         foreach ($c['namespaceMap'] as $nsName => $nsPath) {
             $pdp->loadPolicy($nsName . '\\Authorization\\*.json');
         }
         return $pdp;
     };
     $dc['User'] = function ($dc) {
         $user = $dc['objectInjector'](new \Nethgui\Authorization\User($dc['Session'], $dc['Log']));
         $user->setAuthenticationValidator($dc['user.authenticate']);
         return $user;
     };
     $objectInjector = function ($o) use($dc) {
         if ($o instanceof \Nethgui\Component\DependencyInjectorAggregate) {
             $o->setDependencyInjector($dc['objectInjector']);
         }
         if ($o instanceof \Nethgui\Component\DependencyConsumer) {
             foreach ($o->getDependencySetters() as $key => $setter) {
                 if (!isset($dc[$key])) {
                     continue;
                 }
                 call_user_func($setter, $dc[$key]);
             }
         }
         if ($o instanceof \Nethgui\Log\LogConsumerInterface) {
             $o->setLog($dc['Log']);
         }
         if ($o instanceof \Nethgui\Utility\SessionConsumerInterface) {
             $o->setSession($dc['Session']);
         }
         if ($o instanceof Authorization\PolicyEnforcementPointInterface) {
             $o->setPolicyDecisionPoint($dc['Pdp']);
         }
         if ($o instanceof \Nethgui\System\PlatformConsumerInterface) {
             $o->setPlatform($dc['Platform']);
         }
         return $o;
     };
     $dc['objectInjector'] = $dc->protect($objectInjector);
     $dc['StaticFiles'] = function ($c) {
         return $c['objectInjector'](new \Nethgui\Model\StaticFiles(), $c);
     };
     $dc['UserNotifications'] = function ($c) {
         return $c['objectInjector'](new \Nethgui\Model\UserNotifications(), $c);
     };
     $dc['ValidationErrors'] = function ($c) {
         return $c['objectInjector'](new \Nethgui\Model\ValidationErrors(), $c);
     };
     $dc['SystemTasks'] = function ($c) {
         return $c['objectInjector'](new \Nethgui\Model\SystemTasks($c['Log']), $c);
     };
     $dc['FilenameResolver'] = $this->getFileNameResolver();
     $dc['ModuleSet'] = function ($c) {
         $moduleSet = new \Nethgui\Module\ModuleLoader($c['objectInjector']);
         foreach ($c['namespaceMap'] as $nsName => $nsRoot) {
             if ($nsName === 'Nethgui') {
                 $nsRoot = FALSE;
             }
             $moduleSet->setNamespace($nsName . '\\Module', $nsRoot);
         }
         return $c['objectInjector'](new \Nethgui\Authorization\AuthorizedModuleSet($moduleSet, $c['User']), $c);
     };
     $dc['Platform'] = function ($c) {
         return $c['objectInjector'](new \Nethgui\System\NethPlatform($c['User'], $c['SystemTasks']), $c);
     };
     $dc['Translator'] = function ($c) {
         return $c['objectInjector'](new \Nethgui\View\Translator($c['OriginalRequest']->getLanguageCode(), $c['l10n.catalog_resolver'], array_keys($c['namespaceMap'])), $c);
     };
     $dc['HttpResponse'] = function ($c) {
         return new \Nethgui\Utility\HttpResponse();
     };
     $dc['Main.factory'] = $dc->factory(function ($c) {
         return $c['objectInjector'](new \Nethgui\Module\Main($c['ModuleSet'], $c['main.default_module']), $c);
     });
     $dc['View'] = function ($c) use(&$urlParts) {
         $rootView = $c['objectInjector'](new \Nethgui\View\View($c['OriginalRequest']->getFormat(), $c['Main'], $c['Translator'], $urlParts), $c);
         $rootView->setTemplate(FALSE);
         /*
          *  FIXME: remove deprecated features in version 2.0
          */
         $rootView->commands = $c['objectInjector'](new \Nethgui\View\LegacyCommandBag($rootView, $c), $c);
         /*
          *
          */
         return $rootView;
     };
     $dc['decorator.xhtml.params'] = function ($dc) {
         return new \ArrayObject(array('disableHeader' => FALSE, 'disableMenu' => FALSE, 'disableFooter' => TRUE));
     };
     $dc['main.xhtml.template'] = $dc->protect(function (\Nethgui\Renderer\Xhtml $renderer, $T, \Nethgui\Utility\HttpResponse $httpResponse) use($dc, &$urlParts) {
         $decoratorView = $dc['objectInjector'](new \Nethgui\View\View($dc['OriginalRequest']->getFormat(), $dc['Main'], $dc['Translator'], $urlParts), $dc);
         $decoratorView->setTemplate($dc['decorator.xhtml.template']);
         $decoratorView->copyFrom($renderer);
         $decoratorView->copyFrom($dc['decorator.xhtml.params']);
         $decoratorView['lang'] = $dc['Translator']->getLanguageCode();
         $decoratorView['username'] = $dc['User']->asAuthorizationString();
         $decoratorView['currentModuleOutput'] = 'currentModule';
         // Override helpAreaOutput
         $decoratorView['helpAreaOutput'] = (string) $renderer->panel($renderer::STATE_UNOBTRUSIVE)->setAttribute('class', 'HelpArea')->insert($renderer->panel()->setAttribute('class', 'wrap')->insert($renderer->buttonList($renderer::BUTTONSET)->insert($renderer->button('Hide', $renderer::BUTTON_CANCEL))));
         $currentModule = $renderer['moduleView']->getModule();
         // Override currentModuleOutput
         // - We must render CurrentModule before NotificationArea to catch notifications
         if ($currentModule instanceof \Nethgui\Module\ModuleCompositeInterface) {
             $decoratorView['currentModuleOutput'] = (string) $renderer->inset('moduleView');
         } else {
             $decoratorView['currentModuleOutput'] = (string) $renderer->panel()->setAttribute('class', 'Controller')->insert($renderer->inset('moduleView', $renderer::INSET_FORM | $renderer::INSET_WRAP)->setAttribute('class', 'Action')->setAttribute('receiver', $currentModule->getIdentifier()));
         }
         $decoratorView['trackerOutput'] = (string) $renderer->inset('Tracker', $renderer::STATE_UNOBTRUSIVE);
         // Override menuOutput
         $decoratorView['menuOutput'] = (string) $renderer->inset('Menu');
         // Override notificationOutput. Render Notification at the end, to catch notifications from other modules.
         $decoratorView['notificationOutput'] = (string) $renderer->inset('Notification');
         $decoratorView['moduleTitle'] = $dc['Translator']->translate($currentModule, $currentModule->getAttributesProvider()->getTitle());
         //read css from db
         $db = $dc['Main']->getPlatform()->getDatabase('configuration');
         $colors = $db->getProp('httpd-admin', 'colors');
         if ($colors) {
             $colors = explode(',', $colors);
             $decoratorView['colors'] = $colors;
         }
         $logo = $db->getProp('httpd-admin', 'logo');
         $decoratorView['logo'] = $decoratorView->getPathUrl() . ($logo ? sprintf('images/%s', $logo) : 'images/logo.png');
         $decoratorView['company'] = $db->getProp('OrganizationContact', 'Company');
         $decoratorView['address'] = $db->getProp('OrganizationContact', 'Street') . ", " . $db->getProp('OrganizationContact', 'City');
         $favicon = $db->getProp('httpd-admin', 'favicon');
         $decoratorView['favicon'] = $decoratorView->getPathUrl() . ($favicon ? sprintf('images/%s', $favicon) : 'images/favicon.png');
         return $renderer->spawnRenderer($decoratorView)->render();
     });
     $dc['main.css.template'] = $dc->protect(function (\Nethgui\Renderer\TemplateRenderer $renderer, $T, \Nethgui\Utility\HttpResponse $httpResponse) use($dc) {
         $content = '';
         foreach ($renderer as $value) {
             if ($value instanceof \Nethgui\View\ViewInterface) {
                 $content .= $renderer->spawnRenderer($value)->render();
             } else {
                 $content .= (string) $value;
             }
         }
         return $content;
     });
     $dc['main.js.template'] = $dc['main.css.template'];
     $dc['main.txt.template'] = $dc['main.css.template'];
     $dc['Renderer'] = function ($dc) {
         $filenameResolver = $dc['FilenameResolver'];
         $targetFormat = $dc['OriginalRequest']->getFormat();
         // Set the default root view template
         if (isset($dc[sprintf('main.%s.template', $targetFormat)])) {
             $dc['View']->setTemplate($dc[sprintf('main.%s.template', $targetFormat)]);
         }
         if ($targetFormat === 'json') {
             $renderer = new \Nethgui\Renderer\Json($dc['View']);
         } elseif ($targetFormat === 'xhtml') {
             $renderer = new \Nethgui\Renderer\Xhtml($dc['View'], $filenameResolver, 0);
         } else {
             if ($targetFormat === 'js') {
                 $renderer = new \Nethgui\Renderer\TemplateRenderer($dc['View'], $filenameResolver, 'application/javascript', 'UTF-8');
             } elseif ($targetFormat === 'css') {
                 $renderer = new \Nethgui\Renderer\TemplateRenderer($dc['View'], $filenameResolver, 'text/css', 'UTF-8');
             } else {
                 $renderer = new \Nethgui\Renderer\TemplateRenderer($dc['View'], $filenameResolver, 'text/plain', 'UTF-8');
             }
         }
         $dc['HttpResponse']->addHeader(sprintf('Content-Type: %s', $renderer->getContentType()) . ($renderer->getCharset() ? sprintf('; charset=%s', $renderer->getCharset()) : ''));
         return $dc['objectInjector']($renderer, $dc);
     };
     $this->dc = $dc;
 }
예제 #24
0
파일: di.php 프로젝트: sat8bit/matomepp
<?php

require_once __DIR__ . '/../vendor/autoload.php';
$container = new Pimple\Container();
$container['amqpConnection'] = function ($c) {
    return new PhpAmqpLib\Connection\AMQPConnection('localhost', 5672, 'guest', 'guest');
};
$container['pickupTweetService'] = function ($c) {
    return new sat8bit\Matomepp\Service\PickupTweetService($c['twitteroauth'], $c['pdo']);
};
$container['twitteroauth'] = function ($c) {
    $consumerKey = $c['twitterConfig']['consumer_key'];
    $consumerSecret = $c['twitterConfig']['consumer_secret'];
    $accessToken = $c['twitterConfig']['access_token'];
    $accessTokenSecret = $c['twitterConfig']['access_token_secret'];
    return new Abraham\TwitterOAuth\TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
};
$container['twitterConfig'] = function ($c) {
    return parse_ini_file(__DIR__ . "/../conf/twitter.ini");
};
$container['amqpChannelRssUrl'] = $container->factory(function ($c) {
    $channel = $c['amqpConnection']->channel();
    $channel->queue_declare('rssurl', false, false, false, false);
    return $channel;
});
$container['recommendationRepo'] = $container->factory(function ($c) {
    return new sat8bit\Matomepp\Recommendation\RecommendationRepository($c['pdo']);
});
$container['blogRepo'] = $container->factory(function ($c) {
    return new sat8bit\Matomepp\Blog\BlogRepository($c['pdo']);
});
예제 #25
0
<?php

/**
 * Configure the application container using Pimple
 */
$container = new Pimple\Container();
$container['aws.s3.client'] = $container->factory(function () {
    return new Aws\S3\S3Client(['region' => 'us-east-1', 'credentials' => ['key' => getenv('AWS_ACCESS_KEY_ID'), 'secret' => getenv('AWS_SECRET_ACCESS_KEY')], 'version' => 'latest']);
});
$container['redshift.client'] = $container->factory(function () {
    $dsn = sprintf('pgsql:host=%s;port=%d;dbname=%s;user=%s;password=%s', getenv('REDSHIFT_ENDPOINT'), getenv('REDSHIFT_PORT'), getenv('REDSHIFT_DBNAME'), getenv('REDSHIFT_USER'), getenv('REDSHIFT_PASSWORD'));
    $client = new PDO($dsn);
    $client->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $client;
});
$container['operations.s3-sync'] = $container->factory(function ($c) {
    return new KissmetricsToDatabase\Operations\SyncBucket($c['aws.s3.client'], ['source' => getenv('AWS_S3_BUCKET'), 'destination' => getenv('FILES_DIR')]);
});
$container['operations.file-importer'] = $container->factory(function ($c) {
    return new KissmetricsToDatabase\Operations\FileImporter($c['redshift.client']);
});
$container['command.db-create'] = $container->factory(function () {
    return new KissmetricsToDatabase\Commands\CreateDatabaseCommand();
});
$container['command.process-files'] = $container->factory(function ($c) {
    return new KissmetricsToDatabase\Commands\ProcessFilesCommand(['work_dir' => getenv('WORK_DIR'), 'files_dir' => getenv('FILES_DIR'), 'last_read_file' => getenv('LAST_READ_FILE')]);
});
/**
 * THIS FILE MUST RETURN THE PIMPLE CONTAINER
 */
return $container;
예제 #26
0
파일: index.php 프로젝트: xuedi/pedetes
<?php

// get the locations right
$lib = realpath(dirname(__FILE__));
$app = realpath(dirname($_SERVER["SCRIPT_FILENAME"]) . '/..');
// autoload
define('startTime', microtime(true));
require $lib . '/app/globals.php';
require $lib . '/vendor/autoload.php';
$pebug = \Pedetes\pebug::Instance();
$pebug->init(startTime);
// create injection container
$ctn = new Pimple\Container();
// injected paths
$ctn["pathLib"] = $lib . '/';
$ctn["pathApp"] = $app . '/';
// injected helper
$ctn['session'] = $ctn->factory(function ($ctn) {
    return new Pedetes\session($ctn);
});
$ctn['db'] = $ctn->factory(function ($ctn) {
    return new Pedetes\database($ctn);
});
$ctn['request'] = $ctn->factory(function ($ctn) {
    return new Pedetes\request($ctn);
});
$ctn['cache'] = $ctn->factory(function ($ctn) {
    return new Pedetes\cache($ctn);
});
// start up the app
$app = new Pedetes\bootstrap($ctn);
예제 #27
0
<?php

$package = __DIR__ . '/../../../../vendor/autoload.php';
if (file_exists($package)) {
    require $package;
} else {
    require __DIR__ . '/../vendor/autoload.php';
}
use Expressly\Logger\DummyLogger;
use Expressly\ServiceProvider\MonologServiceProvider;
$app = new Pimple\Container();
require_once __DIR__ . '/config.php';
try {
    $app->register(new MonologServiceProvider($app), array('monolog.name' => $merchantType));
} catch (\Exception $e) {
    $app['logger'] = function () {
        return new DummyLogger();
    };
}
require_once __DIR__ . '/services.php';
return $app;
예제 #28
0
<?php

$startTime = microtime(true);
$startMemory = memory_get_usage();
ini_set('display_errors', 0);
require_once __DIR__ . '/vendor/autoload.php';
$container = new Pimple\Container();
// load the config for the application
$config_path = __DIR__ . '/config.json';
$handle = @fopen($config_path, 'r');
if ($handle === false) {
    throw new RuntimeException("Could not load config");
}
$config = fread($handle, filesize($config_path));
fclose($handle);
$config = json_decode($config);
$last_json_error = json_last_error();
if ($last_json_error !== JSON_ERROR_NONE) {
    throw new RuntimeException("Could not parse config - JSON error detected");
}
$container['config'] = $config;
// timezones are fun
date_default_timezone_set('America/Phoenix');
// todo - belongs in configuration
$container['default_timezone'] = function ($c) {
    return new DateTimeZone('America/Phoenix');
};
// configure the db connections holder
$db_connections = new Aura\Sql\ConnectionLocator();
$db_connections->setDefault(function () use($config) {
    $connection = $config->database->slave;
예제 #29
0
<?php

require dirname(__DIR__) . '/vendor/autoload.php';
// Automatically parse environment configuration (Heroku)
if (getenv('DATABASE_URL')) {
    $dbopts = parse_url(getenv('DATABASE_URL'));
    define('DB_DRIVER', $dbopts['scheme']);
    define('DB_USERNAME', $dbopts["user"]);
    define('DB_PASSWORD', $dbopts["pass"]);
    define('DB_HOSTNAME', $dbopts["host"]);
    define('DB_PORT', isset($dbopts["port"]) ? $dbopts["port"] : null);
    define('DB_NAME', ltrim($dbopts["path"], '/'));
}
// Include custom config file
if (file_exists('config.php')) {
    require 'config.php';
}
require __DIR__ . '/constants.php';
require __DIR__ . '/check_setup.php';
$container = new Pimple\Container();
$container->register(new ServiceProvider\LoggingProvider());
$container->register(new ServiceProvider\DatabaseProvider());
$container->register(new ServiceProvider\ClassProvider());
$container->register(new ServiceProvider\EventDispatcherProvider());
if (ENABLE_URL_REWRITE) {
    require __DIR__ . '/routes.php';
}
$container['pluginLoader']->scan();
예제 #30
0
 /**
  * @param Pimple\Container $pimple
  */
 function let($pimple)
 {
     $pimple->offsetExists(Argument::any())->willReturn(true);
     $this->beConstructedWith($pimple);
 }