Exemplo n.º 1
0
/**
 * @param Symfony\Component\DependencyInjection\ContainerBuilder $container
 */
function api4_civicrm_container($container)
{
    $container->addResource(new \Symfony\Component\Config\Resource\FileResource(__FILE__));
    $container->setDefinition('action_object_provider', new \Symfony\Component\DependencyInjection\Definition('Civi\\API\\Provider\\ActionObjectProvider', array()));
    $container->findDefinition('dispatcher')->addMethodCall('addSubscriber', array(new \Symfony\Component\DependencyInjection\Reference('action_object_provider')));
    $container->findDefinition('civi_api_kernel')->addMethodCall('registerApiProvider', array(new \Symfony\Component\DependencyInjection\Reference('action_object_provider')));
}
Exemplo n.º 2
0
 public function getContainer()
 {
     $container = new \Symfony\Component\DependencyInjection\ContainerBuilder();
     $dispatcher = $this->getMock("Symfony\\Component\\EventDispatcher\\EventDispatcherInterface");
     $container->set("event_dispatcher", $dispatcher);
     return $container;
 }
 /**
  * @param Symfony\Component\DependencyInjection\ContainerBuilder $container
  * @param Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface $parameterBag
  * @param Symfony\Component\DependencyInjection\Definition $libraryDefinition
  * @param Symfony\Component\DependencyInjection\Definition $parserDefinition
  */
 public function it_loads_the_configuration($container, $parameterBag, $libraryDefinition, $parserDefinition)
 {
     $container->getParameterBag()->shouldBeCalled()->willReturn($parameterBag);
     $container->hasExtension(Argument::any())->shouldBeCalled()->willReturn(false);
     $container->addResource(Argument::any())->shouldBeCalled()->willReturn($container);
     foreach (array('dispatcher', 'metadata.driver', 'metadata.factory', 'metadata.reader', 'parser', 'library', 'parser', 'formatter', 'formatter.markdown', 'formatter.textile', 'validator', 'validator.constraint_validator_factory') as $service) {
         $container->setDefinition('fabricius.' . $service, Argument::any())->shouldBeCalled();
     }
     $container->setAlias('fabricius', Argument::any())->shouldBeCalled();
     $container->getDefinition('fabricius.library')->shouldBeCalled()->willReturn($libraryDefinition);
     $libraryDefinition->addMethodCall('registerRepository', Argument::that(function ($args) {
         if ($args[0] !== 'Fabricius\\FabriciusBundle\\ContentItem') {
             return false;
         } elseif ($args[1]->getClass() !== 'Fabricius\\Loader\\FileLoader') {
             return false;
         } elseif ($args[2]->getClass() !== 'Fabricius\\Storage\\ArrayStorage') {
             return false;
         }
         return true;
     }))->shouldBeCalled();
     $container->getDefinition('fabricius.parser')->shouldBeCalled()->willReturn($parserDefinition);
     $parserDefinition->addMethodCall('setExcerptDelimiter', array('[MORE]'))->shouldBeCalled();
     $config = array('excerpt_delimiter' => '[MORE]', 'formatter' => array('markdown' => array('enabled' => true), 'textile' => array('enabled' => true)), 'repositories' => array('Fabricius\\FabriciusBundle\\ContentItem' => array('loader' => array('file' => array('dir' => __DIR__)), 'storage' => array('array' => array('enabled' => true)))));
     $this->load(array('fabricius' => $config), $container)->shouldReturn(null);
 }
 /**
  * @param Symfony\Component\DependencyInjection\ContainerBuilder $container
  * @param Symfony\Component\DependencyInjection\Definition $string
  * @param Symfony\Component\DependencyInjection\Definition $int
  * @param Symfony\Component\DependencyInjection\Definition $boolean
  **/
 function let($container, $string, $int, $boolean)
 {
     $services = ['friendly.faker.provider.string' => null, 'friendly.faker.provider.int' => null, 'friendly.faker.provider.boolean' => null];
     $container->findTaggedServiceIds('friendly.faker.provider')->willReturn($services);
     $container->getDefinition('friendly.faker.provider.string')->willReturn($string);
     $container->getDefinition('friendly.faker.provider.int')->willReturn($int);
     $container->getDefinition('friendly.faker.provider.boolean')->willReturn($boolean);
 }
Exemplo n.º 5
0
 public function getContainer()
 {
     $container = new \Symfony\Component\DependencyInjection\ContainerBuilder();
     $container->set("event_dispatcher", $this->getDispatcher());
     $request = new Request();
     $request->setSession($this->session);
     $container->set("request", $request);
     return $container;
 }
Exemplo n.º 6
0
 public function setUp()
 {
     $container = new \Symfony\Component\DependencyInjection\ContainerBuilder();
     $router = $this->getMockBuilder("Symfony\\Component\\Routing\\Router")->disableOriginalConstructor()->getMock();
     $this->context = new \Symfony\Component\Routing\RequestContext('/thelia/index.php', 'GET', 'localhost', 'http', 80, 443, '/path/to/action');
     $router->expects($this->any())->method('getContext')->will($this->returnValue($this->context));
     $container->set("router.admin", $router);
     new URL($container);
 }
Exemplo n.º 7
0
 public function getContainer()
 {
     $container = new \Symfony\Component\DependencyInjection\ContainerBuilder();
     $dispatcher = $this->getMock("Symfony\\Component\\EventDispatcher\\EventDispatcherInterface");
     $container->set("event_dispatcher", $dispatcher);
     $fileManager = new FileManager(["document.product" => "Thelia\\Model\\ProductDocument", "image.product" => "Thelia\\Model\\ProductImage", "document.category" => "Thelia\\Model\\CategoryDocument", "image.category" => "Thelia\\Model\\CategoryImage", "document.content" => "Thelia\\Model\\ContentDocument", "image.content" => "Thelia\\Model\\ContentImage", "document.folder" => "Thelia\\Model\\FolderDocument", "image.folder" => "Thelia\\Model\\FolderImage", "document.brand" => "Thelia\\Model\\BrandDocument", "image.brand" => "Thelia\\Model\\BrandImage"]);
     $container->set("thelia.file_manager", $this->getFileManager());
     $request = new Request();
     $request->setSession($this->session);
     $container->set("request", $request);
     return $container;
 }
Exemplo n.º 8
0
/**
 * @return \ProjectServiceContainer|\Symfony\Component\DependencyInjection\Container
 */
function symfonyFromConfig($config)
{
    $file = TEMP_DIR . '/container.php';
    $container = new \Symfony\Component\DependencyInjection\ContainerBuilder();
    $container->addCompilerPass(new \Symfony\Component\DependencyInjection\Compiler\AutowirePass());
    $loader = new \Symfony\Component\DependencyInjection\Loader\YamlFileLoader($container, new \Symfony\Component\Config\FileLocator(TEMP_DIR));
    $loader->load(asfile('config.yml', $config));
    $container->compile();
    $dumper = new \Symfony\Component\DependencyInjection\Dumper\PhpDumper($container);
    file_put_contents($file, $dumper->dump());
    require_once $file;
    return new ProjectServiceContainer();
}
Exemplo n.º 9
0
 protected function setUp($enabled = true)
 {
     $this->transport = $this->getMockBuilder('Kuborgh\\LogentriesBundle\\Transport\\TransportInterface')->getMock();
     $container = new \Symfony\Component\DependencyInjection\ContainerBuilder();
     $request = new \Symfony\Component\HttpFoundation\Request();
     $container->set('request', $request);
     $this->logger = new Logger($container, get_class($this->transport), array(), $enabled);
     // Inject transport
     $reflClass = new ReflectionClass(get_class($this->logger));
     $refl = $reflClass->getProperty('transport');
     $refl->setAccessible(true);
     $refl->setValue($this->logger, $this->transport);
 }
 /**
  * @param Symfony\Component\DependencyInjection\ContainerBuilder $container
  * @param Symfony\Component\DependencyInjection\Definition $manager
  * @param Symfony\Component\DependencyInjection\Definition $string
  * @param Symfony\Component\DependencyInjection\Definition $int
  * @param Symfony\Component\DependencyInjection\Definition $boolean
  **/
 function let($container, $manager, $string, $int, $boolean)
 {
     $services = ['friendly.guesser.string' => null, 'friendly.guesser.int' => null, 'friendly.guesser.boolean' => null];
     $stringFaker = ['friendly.faker.provider.address' => null, 'friendly.faker.provider.person' => null, 'friendly.faker.provider.internet' => null];
     $intFaker = ['friendly.faker.provider.payment' => null];
     $container->findTaggedServiceIds('friendly.format.guesser')->willReturn($services);
     $container->findTaggedServiceIds('friendly.guesser.string.faker')->willReturn($stringFaker);
     $container->findTaggedServiceIds('friendly.guesser.int.faker')->willReturn($intFaker);
     $container->findTaggedServiceIds('friendly.guesser.boolean.faker')->willReturn([]);
     $container->getDefinition('friendly.guesser.manager')->willReturn($manager);
     $container->getDefinition('friendly.guesser.string')->willReturn($string);
     $container->getDefinition('friendly.guesser.int')->willReturn($int);
     $container->getDefinition('friendly.guesser.boolean')->willReturn($boolean);
 }
Exemplo n.º 11
0
<?php

include_once '../vendor/autoload.php';
$certData = array();
$certData['passphrase'] = 'test1234';
$certData['certificate'] = file_get_contents('./cert/example.crt');
$certData['privatekey'] = file_get_contents('./cert/example.pem');
$container = new Symfony\Component\DependencyInjection\ContainerBuilder();
$container->setParameter('NameID', 'testNameId');
$container->setParameter('Issuer', 'http://saml.dev.wizkunde.nl/');
$container->setParameter('MetadataExpirationTime', 604800);
$container->setParameter('SPReturnUrl', 'http://return.wizkunde.nl/');
$container->setParameter('ForceAuthn', 'true');
$container->setParameter('IsPassive', 'false');
$container->setParameter('NameIDFormat', 'testNameId');
$container->setParameter('ComparisonLevel', 'exact');
$container->register('twig_loader', 'Twig_Loader_Filesystem')->addArgument('../src/Wizkunde/SAMLBase/Template/Twig');
$container->register('twig', 'Twig_Environment')->addArgument(new Symfony\Component\DependencyInjection\Reference('twig_loader'));
$container->register('SigningCertificate', 'Wizkunde\\SAMLBase\\Certificate')->addArgument($certData['privatekey'])->addArgument($certData['certificate'])->addArgument($certData['passphrase']);
$container->register('EncryptionCertificate', 'Wizkunde\\SAMLBase\\Certificate')->addArgument($certData['privatekey'])->addArgument($certData['certificate'])->addArgument($certData['passphrase']);
$container->register('encryption', 'Wizkunde\\SAMLBase\\Security\\Encryption')->addMethodCall('setCertificate', array(new Symfony\Component\DependencyInjection\Reference('EncryptionCertificate')));
$container->register('signature', 'Wizkunde\\SAMLBase\\Security\\Signature')->addMethodCall('setCertificate', array(new Symfony\Component\DependencyInjection\Reference('SigningCertificate')));
$container->register('unique_id_generator', 'Wizkunde\\SAMLBase\\Configuration\\UniqueID');
$container->register('timestamp_generator', 'Wizkunde\\SAMLBase\\Configuration\\Timestamp');
/**
 * Setup the Metadata resolve service
 */
$container->register('guzzle_http', 'Guzzle\\Http\\Client');
$container->register('resolver', 'Wizkunde\\SAMLBase\\Metadata\\ResolveService')->addArgument(new Symfony\Component\DependencyInjection\Reference('guzzle_http'));
/**
 * Resolve the metadata
 /**
  * @param Symfony\Component\DependencyInjection\ContainerBuilder $container
  */
 public function it_only_processes_when_definition_exists($container)
 {
     $container->hasDefinition('fabricius.dispatcher')->shouldBeCalled()->willReturn(false);
     $container->getDefinition('fabricius.dispatcher')->shouldNotBeCalled();
     $this->process($container);
 }
Exemplo n.º 13
0
 public function dispatchProfileInitEvent(InputInterface $sessionInput, OutputInterface $output)
 {
     $event = new Event\ProfileInitEvent($this->container->get('config.profile'), $sessionInput, $output);
     $this->dispatcher->dispatch(PhpcrShellEvents::PROFILE_INIT, $event);
 }
Exemplo n.º 14
0
 public function testContainer()
 {
     $container = new \Symfony\Component\DependencyInjection\ContainerBuilder();
     $container->register('test_service', 'TestService');
     $this->assertInstanceOf('TestService', $container->get('test_service'));
 }
 /**
  * @param Symfony\Component\DependencyInjection\ContainerBuilder $container
  */
 public function it_add_complier_pass_during_build($container)
 {
     $container->addCompilerPass(Argument::type('Fabricius\\Bundle\\FabriciusBundle\\DependencyInjection\\Compiler\\AddFormatHandlerPass'))->shouldBeCalled();
     $container->addCompilerPass(Argument::type('Fabricius\\Bundle\\FabriciusBundle\\DependencyInjection\\Compiler\\AddListenerPass'))->shouldBeCalled();
     $this->build($container);
 }
<?php

$file = __DIR__ . '/container_test6.php';
if (file_exists($file)) {
    require_once $file;
    $container = new ProjectServiceContainer();
} else {
    $container = new Symfony\Component\DependencyInjection\ContainerBuilder();
    $classes = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];
    for ($i = 0; $i < count($classes); $i++) {
        if (isset($classes[$i - 1])) {
            $ref = [new Symfony\Component\DependencyInjection\Reference($classes[$i - 1])];
        } else {
            $ref = [];
        }
        $definition = new Symfony\Component\DependencyInjection\Definition($classes[$i], $ref);
        $definition->setScope('prototype');
        $container->setDefinition($classes[$i], $definition);
    }
    $container->compile();
    $dumper = new Symfony\Component\DependencyInjection\Dumper\PhpDumper($container);
    file_put_contents($file, $dumper->dump());
}
//Trigger autoloader
$a = $container->get('J');
unset($a);
$t1 = microtime(true);
for ($i = 0; $i < 10000; $i++) {
    $a = $container->get('J');
}
$t2 = microtime(true);
Exemplo n.º 17
0
<?php

require_once __DIR__ . '/../../vendor/autoload.php';
class Processor implements \Amqp\Util\Interfaces\Processor
{
    public function process(\AMQPEnvelope $message)
    {
        echo 'FOO:' . $message->getBody() . "\n";
        return "test-response";
    }
}
class Processor2 extends Processor
{
    public function process(\AMQPEnvelope $message)
    {
        parent::process($message);
        echo 'BAR:' . $message->getBody() . "\n";
        return "test-response2";
    }
}
$container = new \Symfony\Component\DependencyInjection\ContainerBuilder();
$loader = new \Symfony\Component\DependencyInjection\Loader\YamlFileLoader($container, new \Symfony\Component\Config\FileLocator(__DIR__ . '/config'));
$loader->load('services.yml');
$container->setParameter('config_path', __DIR__ . '/config');
$listener = $container->get('listener.demo');
$listener->listen();
Exemplo n.º 18
0
         return;
     }
     if (strpos($class, '\\') !== false && strpos($class, 'Model\\') === false && strpos($class, 'Database\\') === false) {
         return;
     }
     $namespaced = 'Contao\\' . $class;
     if (class_exists($namespaced) || interface_exists($namespaced) || trait_exists($namespaced)) {
         class_alias($namespaced, $class);
     }
 });
 define('TL_ROOT', __DIR__ . '/../../../../vendor/contao/core');
 #require_once __DIR__ . '/../../../../vendor/contao/core/system/helper/ide_compat.php';
 require_once TL_ROOT . '/system/helper/functions.php';
 // Container in Contao 4
 if (method_exists('System', 'getContainer')) {
     $container = new \Symfony\Component\DependencyInjection\ContainerBuilder(new \Symfony\Component\DependencyInjection\ParameterBag\ParameterBag(['kernel.cache_dir' => sys_get_temp_dir(), 'kernel.bundles' => ['ChangeLanguage']]));
     $container->set('contao.resource_locator', new \Symfony\Component\Config\FileLocator([__DIR__ . '/../../../../']));
     $container->set('contao.resource_finder', new \Contao\CoreBundle\Config\ResourceFinder([__DIR__ . '/../../../../']));
     System::setContainer($container);
 }
 class Config extends \Contao\Config
 {
     protected function initialize()
     {
         parent::initialize();
         $GLOBALS['TL_CONFIG']['dbDriver'] = 'MySQLi';
         $GLOBALS['TL_CONFIG']['dbUser'] = $GLOBALS['DB_USER'];
         $GLOBALS['TL_CONFIG']['dbPass'] = $GLOBALS['DB_PASSWD'];
         $GLOBALS['TL_CONFIG']['dbHost'] = $GLOBALS['DB_HOST'];
         $GLOBALS['TL_CONFIG']['dbDatabase'] = $GLOBALS['DB_DBNAME'];
         $GLOBALS['TL_CONFIG']['dbPort'] = $GLOBALS['DB_PORT'];
<?php

$file = __DIR__ . '/container_test5.php';
if (file_exists($file)) {
    require_once $file;
    $container = new ProjectServiceContainer();
} else {
    $container = new Symfony\Component\DependencyInjection\ContainerBuilder();
    $container->register('A', 'A');
    $ref = [new Symfony\Component\DependencyInjection\Reference('A')];
    $definition = new Symfony\Component\DependencyInjection\Definition('B', $ref);
    $definition->setScope('prototype');
    $container->setDefinition('B', $definition);
    $container->compile();
    $dumper = new Symfony\Component\DependencyInjection\Dumper\PhpDumper($container);
    file_put_contents($file, $dumper->dump());
}
//trigger autoloader
$a = $container->get('B');
unset($a);
$t1 = microtime(true);
for ($i = 0; $i < 10000; $i++) {
    $a = $container->get('B');
}
$t2 = microtime(true);
$results = ['time' => $t2 - $t1, 'files' => count(get_included_files()), 'memory' => memory_get_peak_usage() / 1024 / 1024];
echo json_encode($results);
<?php

$file = __DIR__ . '/container_test1.php';
if (file_exists($file)) {
    require_once $file;
    $container = new ProjectServiceContainer();
} else {
    $container = new Symfony\Component\DependencyInjection\ContainerBuilder();
    $definition = new Symfony\Component\DependencyInjection\Definition('A', []);
    $definition->setScope('prototype');
    $container->setDefinition('A', $definition);
    $container->compile();
    $dumper = new Symfony\Component\DependencyInjection\Dumper\PhpDumper($container);
    file_put_contents($file, $dumper->dump());
}
//Trigger the autoloader
$a = $container->get('A');
unset($a);
$t1 = microtime(true);
for ($i = 0; $i < 10000; $i++) {
    $a = $container->get('A');
}
$t2 = microtime(true);
$results = ['time' => $t2 - $t1, 'files' => count(get_included_files()), 'memory' => memory_get_peak_usage() / 1024 / 1024];
echo json_encode($results);
Exemplo n.º 21
0
<?php

// Configure DI Container
$container = new \Symfony\Component\DependencyInjection\ContainerBuilder();
$loader = new \Symfony\Component\DependencyInjection\Loader\XmlFileLoader($container);
$loader->load(realpath(APPLICATION_PATH . '/../config') . '/di/services.xml');
// Get Entity Manager from DI Container
$entityManager = $container->get('doctrine.orm');
// Configure Helpers
$helperSet = new \Symfony\Component\Console\Helper\HelperSet(array('db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($entityManager->getConnection()), 'dialog' => new \Symfony\Component\Console\Helper\DialogHelper(), 'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($entityManager)));
Exemplo n.º 22
0
 /**
  * Entry-point for Erebot.
  *
  * \return
  *      This method never returns.
  *      Instead, the program exits with an appropriate
  *      return code when Erebot is stopped.
  */
 public static function run()
 {
     // Apply patches.
     \Erebot\Patches::patch();
     // Load the configuration for the Dependency Injection Container.
     $dic = new \Symfony\Component\DependencyInjection\ContainerBuilder();
     $dic->setParameter('Erebot.src_dir', __DIR__);
     $loader = new \Symfony\Component\DependencyInjection\Loader\XmlFileLoader($dic, new \Symfony\Component\Config\FileLocator(getcwd()));
     $dicConfig = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'defaults.xml';
     $dicCwdConfig = getcwd() . DIRECTORY_SEPARATOR . 'defaults.xml';
     if (!strncasecmp(__FILE__, 'phar://', 7)) {
         if (!file_exists($dicCwdConfig)) {
             copy($dicConfig, $dicCwdConfig);
         }
         $dicConfig = $dicCwdConfig;
     } elseif (file_exists($dicCwdConfig)) {
         $dicConfig = $dicCwdConfig;
     }
     $loader->load($dicConfig);
     // Determine availability of PHP extensions
     // needed by some of the command-line options.
     $hasPosix = in_array('posix', get_loaded_extensions());
     $hasPcntl = in_array('pcntl', get_loaded_extensions());
     $logger = $dic->get('logging');
     $localeGetter = $dic->getParameter('i18n.default_getter');
     $coreTranslatorCls = $dic->getParameter('core.classes.i18n');
     $translator = new $coreTranslatorCls("Erebot\\Core");
     $categories = array('LC_MESSAGES', 'LC_MONETARY', 'LC_TIME', 'LC_NUMERIC');
     foreach ($categories as $category) {
         $locales = call_user_func($localeGetter);
         $locales = empty($locales) ? array() : array($locales);
         $localeSources = array('LANGUAGE' => true, 'LC_ALL' => false, $category => false, 'LANG' => false);
         foreach ($localeSources as $source => $multiple) {
             if (!isset($_SERVER[$source])) {
                 continue;
             }
             if ($multiple) {
                 $locales = explode(':', $_SERVER[$source]);
             } else {
                 $locales = array($_SERVER[$source]);
             }
             break;
         }
         $translator->setLocale($translator->nameToCategory($category), $locales);
     }
     // Also, include some information about the version
     // of currently loaded PHAR modules, if any.
     $version = 'dev-master';
     if (!strncmp(__FILE__, 'phar://', 7)) {
         $phar = new \Phar(\Phar::running(true));
         $md = $phar->getMetadata();
         $version = $md['version'];
     }
     if (defined('Erebot_PHARS')) {
         $phars = unserialize(Erebot_PHARS);
         ksort($phars);
         foreach ($phars as $module => $metadata) {
             if (strncasecmp($module, 'Erebot_Module_', 14)) {
                 continue;
             }
             $version .= "\n  with {$module} version {$metadata['version']}";
         }
     }
     \Console_CommandLine::registerAction('StoreProxy', '\\Erebot\\Console\\StoreProxyAction');
     $parser = new \Console_CommandLine(array('name' => 'Erebot', 'description' => $translator->gettext('A modular IRC bot written in PHP'), 'version' => $version, 'add_help_option' => true, 'add_version_option' => true, 'force_posix' => false));
     $parser->accept(new \Erebot\Console\MessageProvider());
     $parser->renderer->options_on_different_lines = true;
     $defaultConfigFile = getcwd() . DIRECTORY_SEPARATOR . 'Erebot.xml';
     $parser->addOption('config', array('short_name' => '-c', 'long_name' => '--config', 'description' => $translator->gettext('Path to the configuration file to use instead ' . 'of "Erebot.xml", relative to the current ' . 'directory.'), 'help_name' => 'FILE', 'action' => 'StoreString', 'default' => $defaultConfigFile));
     $parser->addOption('daemon', array('short_name' => '-d', 'long_name' => '--daemon', 'description' => $translator->gettext('Run the bot in the background (daemon).' . ' [requires the POSIX and pcntl extensions]'), 'action' => 'StoreTrue'));
     $noDaemon = new \Erebot\Console\ParallelOption('no_daemon', array('short_name' => '-n', 'long_name' => '--no-daemon', 'description' => $translator->gettext('Do not run the bot in the background. ' . 'This is the default, unless the -d option ' . 'is used or the bot is configured otherwise.'), 'action' => 'StoreProxy', 'action_params' => array('option' => 'daemon')));
     $parser->addOption($noDaemon);
     $parser->addOption('pidfile', array('short_name' => '-p', 'long_name' => '--pidfile', 'description' => $translator->gettext("Store the bot's PID in this file."), 'help_name' => 'FILE', 'action' => 'StoreString', 'default' => null));
     $parser->addOption('group', array('short_name' => '-g', 'long_name' => '--group', 'description' => $translator->gettext('Set group identity to this GID/group during ' . 'startup. The default is to NOT change group ' . 'identity, unless configured otherwise.' . ' [requires the POSIX extension]'), 'help_name' => 'GROUP/GID', 'action' => 'StoreString', 'default' => null));
     $parser->addOption('user', array('short_name' => '-u', 'long_name' => '--user', 'description' => $translator->gettext('Set user identity to this UID/username during ' . 'startup. The default is to NOT change user ' . 'identity, unless configured otherwise.' . ' [requires the POSIX extension]'), 'help_name' => 'USER/UID', 'action' => 'StoreString', 'default' => null));
     try {
         $parsed = $parser->parse();
     } catch (\Exception $exc) {
         $parser->displayError($exc->getMessage());
         exit(1);
     }
     // Parse the configuration file.
     $config = new \Erebot\Config\Main($parsed->options['config'], \Erebot\Config\Main::LOAD_FROM_FILE, $translator);
     $coreCls = $dic->getParameter('core.classes.core');
     $bot = new $coreCls($config, $translator);
     $dic->set('bot', $bot);
     // Use values from the XML configuration file
     // if there is no override from the command line.
     $overrides = array('daemon' => 'mustDaemonize', 'group' => 'getGroupIdentity', 'user' => 'getUserIdentity', 'pidfile' => 'getPidfile');
     foreach ($overrides as $option => $func) {
         if ($parsed->options[$option] === null) {
             $parsed->options[$option] = $config->{$func}();
         }
     }
     /* Handle daemonization.
      * See also:
      * - http://www.itp.uzh.ch/~dpotter/howto/daemonize
      * - http://andytson.com/blog/2010/05/daemonising-a-php-cli-script
      */
     if ($parsed->options['daemon']) {
         if (!$hasPosix) {
             $logger->error($translator->gettext('The posix extension is required in order ' . 'to start the bot in the background'));
             exit(1);
         }
         if (!$hasPcntl) {
             $logger->error($translator->gettext('The pcntl extension is required in order ' . 'to start the bot in the background'));
             exit(1);
         }
         foreach (array('SIGCHLD', 'SIGUSR1', 'SIGALRM') as $signal) {
             if (defined($signal)) {
                 pcntl_signal(constant($signal), array(__CLASS__, 'startupSighandler'));
             }
         }
         $logger->info($translator->gettext('Starting the bot in the background...'));
         $pid = pcntl_fork();
         if ($pid < 0) {
             $logger->error($translator->gettext('Could not start in the background (unable to fork)'));
             exit(1);
         }
         if ($pid > 0) {
             pcntl_wait($dummy, WUNTRACED);
             pcntl_alarm(2);
             pcntl_signal_dispatch();
             exit(1);
         }
         $parent = posix_getppid();
         // Ignore some of the signals.
         foreach (array('SIGTSTP', 'SIGTOU', 'SIGTIN', 'SIGHUP') as $signal) {
             if (defined($signal)) {
                 pcntl_signal(constant($signal), SIG_IGN);
             }
         }
         // Restore the signal handlers we messed with.
         foreach (array('SIGCHLD', 'SIGUSR1', 'SIGALRM') as $signal) {
             if (defined($signal)) {
                 pcntl_signal(constant($signal), SIG_DFL);
             }
         }
         umask(0);
         if (umask() != 0) {
             $logger->warning($translator->gettext('Could not change umask'));
         }
         if (posix_setsid() == -1) {
             $logger->error($translator->gettext('Could not start in the background (unable to setsid)'));
             exit(1);
         }
         // Prevent the child from ever acquiring a controlling terminal.
         // Not required under Linux, but required by at least System V.
         $pid = pcntl_fork();
         if ($pid < 0) {
             $logger->error($translator->gettext('Could not start in the background (unable to fork)'));
             exit(1);
         }
         if ($pid > 0) {
             exit(0);
         }
         // Avoid locking up the current directory.
         if (!chdir(DIRECTORY_SEPARATOR)) {
             $logger->error($translator->gettext('Could not chdir to "%(path)s"'), array('path' => DIRECTORY_SEPARATOR));
         }
         // Explicitly close the magic stream-constants (just in case).
         foreach (array('STDIN', 'STDOUT', 'STDERR') as $stream) {
             if (defined($stream)) {
                 fclose(constant($stream));
             }
         }
         // Re-open them with the system's blackhole.
         /**
          * \todo
          *      should be made portable, but the requirement on the POSIX
          *      extension prevents this, so this is okay for now.
          */
         $stdin = fopen('/dev/null', 'r');
         $stdout = fopen('/dev/null', 'w');
         $stderr = fopen('/dev/null', 'w');
         if (defined('SIGUSR1')) {
             posix_kill($parent, SIGUSR1);
         }
         $logger->info($translator->gettext('Successfully started in the background'));
     }
     try {
         /// @TODO: Check the interface or something like that.
         $identd = $dic->get('identd');
     } catch (\InvalidArgumentException $e) {
         $identd = null;
     }
     try {
         /// @TODO: Check the interface or something like that.
         $prompt = $dic->get('prompt');
     } catch (\InvalidArgumentException $e) {
         $prompt = null;
     }
     // Change group identity if necessary.
     if ($parsed->options['group'] !== null && $parsed->options['group'] != '') {
         if (!$hasPosix) {
             $logger->warning($translator->gettext('The posix extension is needed in order ' . 'to change group identity.'));
         } elseif (posix_getuid() !== 0) {
             $logger->warning($translator->gettext('Only root can change group identity! ' . 'Your current UID is %(uid)d'), array('uid' => posix_getuid()));
         } else {
             if (ctype_digit($parsed->options['group'])) {
                 $info = posix_getgrgid((int) $parsed->options['group']);
             } else {
                 $info = posix_getgrnam($parsed->options['group']);
             }
             if ($info === false) {
                 $logger->error($translator->gettext('No such group "%(group)s"'), array('group' => $parsed->options['group']));
                 exit(1);
             }
             if (!posix_setgid($info['gid'])) {
                 $logger->error($translator->gettext('Could not set group identity ' . 'to "%(name)s" (%(id)d)'), array('id' => $info['gid'], 'name' => $info['name']));
                 exit(1);
             }
             $logger->debug($translator->gettext('Successfully changed group identity ' . 'to "%(name)s" (%(id)d)'), array('name' => $info['name'], 'id' => $info['gid']));
         }
     }
     // Change user identity if necessary.
     if ($parsed->options['user'] !== null || $parsed->options['user'] != '') {
         if (!$hasPosix) {
             $logger->warning($translator->gettext('The posix extension is needed in order ' . 'to change user identity.'));
         } elseif (posix_getuid() !== 0) {
             $logger->warning($translator->gettext('Only root can change user identity! ' . 'Your current UID is %(uid)d'), array('uid' => posix_getuid()));
         } else {
             if (ctype_digit($parsed->options['user'])) {
                 $info = posix_getpwuid((int) $parsed->options['user']);
             } else {
                 $info = posix_getpwnam($parsed->options['user']);
             }
             if ($info === false) {
                 $logger->error($translator->gettext('No such user "%(user)s"'), array('user' => $parsed->options['user']));
                 exit(1);
             }
             if (!posix_setuid($info['uid'])) {
                 $logger->error($translator->gettext('Could not set user identity ' . 'to "%(name)s" (%(id)d)'), array('name' => $info['name'], 'id' => $info['uid']));
                 exit(1);
             }
             $logger->debug($translator->gettext('Successfully changed user identity ' . 'to "%(name)s" (%(id)d)'), array('name' => $info['name'], 'id' => $info['uid']));
         }
     }
     // Write new pidfile.
     if ($parsed->options['pidfile'] !== null && $parsed->options['pidfile'] != '') {
         $pid = @file_get_contents($parsed->options['pidfile']);
         // If the file already existed, the bot may already be started
         // or it may contain data not related to Erebot at all.
         if ($pid !== false) {
             $pid = (int) rtrim($pid);
             if (!$pid) {
                 $logger->error($translator->gettext('The pidfile (%(pidfile)s) contained garbage. ' . 'Exiting'), array('pidfile' => $parsed->options['pidfile']));
                 exit(1);
             } else {
                 posix_kill($pid, 0);
                 $res = posix_errno();
                 switch ($res) {
                     case 0:
                         // No error.
                         $logger->error($translator->gettext('Erebot is already running ' . 'with PID %(pid)d'), array('pid' => $pid));
                         exit(1);
                     case 3:
                         // ESRCH.
                         $logger->warning($translator->gettext('Found stalled PID %(pid)d in pidfile ' . '"%(pidfile)s". Removing it'), array('pidfile' => $parsed->options['pidfile'], 'pid' => $pid));
                         @unlink($parsed->options['pidfile']);
                         break;
                     case 1:
                         // EPERM.
                         $logger->error($translator->gettext('Found another program\'s PID %(pid)d in ' . 'pidfile "%(pidfile)s". Exiting'), array('pidfile' => $parsed->options['pidfile'], 'pid' => $pid));
                         exit(1);
                     default:
                         $logger->error($translator->gettext('Unknown error while checking for ' . 'the existence of another running ' . 'instance of Erebot (%(error)s)'), array('error' => posix_get_last_error()));
                         exit(1);
                 }
             }
         }
         $pidfile = fopen($parsed->options['pidfile'], 'wt');
         flock($pidfile, LOCK_EX | LOCK_NB, $wouldBlock);
         if ($wouldBlock) {
             $logger->error($translator->gettext('Could not lock pidfile (%(pidfile)s). ' . 'Is the bot already running?'), array('pidfile' => $parsed->options['pidfile']));
             exit(1);
         }
         $pid = sprintf("%u\n", getmypid());
         $res = fwrite($pidfile, $pid);
         if ($res !== strlen($pid)) {
             $logger->error($translator->gettext('Unable to write PID to pidfile (%(pidfile)s)'), array('pidfile' => $parsed->options['pidfile']));
             exit(1);
         }
         $logger->debug($translator->gettext('PID (%(pid)d) written into %(pidfile)s'), array('pidfile' => $parsed->options['pidfile'], 'pid' => getmypid()));
         // Register a callback to remove the pidfile upon exit.
         register_shutdown_function(array(__CLASS__, 'cleanupPidfile'), $pidfile, $parsed->options['pidfile']);
     }
     // Display a desperate warning when run as user root.
     if ($hasPosix && posix_getuid() === 0) {
         $logger->warning($translator->gettext('You SHOULD NOT run Erebot as root!'));
     }
     if ($identd !== null) {
         $identd->connect();
     }
     if ($prompt !== null) {
         $prompt->connect();
     }
     // This doesn't return until we purposely
     // make the bot drop all active connections.
     $bot->start($dic->get('factory.connection'));
     exit(0);
 }
Exemplo n.º 23
0
 /**
  * @param Symfony\Component\DependencyInjection\ContainerBuilder $container
  **/
 function let($container)
 {
     $container->setParameter(Argument::cetera())->willReturn(null);
 }
Exemplo n.º 24
0
<?php

require_once __DIR__ . '/../../vendor/autoload.php';
class ProcessorRpc implements \Amqp\Util\Interfaces\TimeoutProcessor
{
    public function process(\AMQPEnvelope $message)
    {
        print_r($message);
    }
    public function timeout()
    {
        echo "Timeout\n";
    }
}
$container = new \Symfony\Component\DependencyInjection\ContainerBuilder();
$loader = new \Symfony\Component\DependencyInjection\Loader\YamlFileLoader($container, new \Symfony\Component\Config\FileLocator(__DIR__ . '/config'));
$loader->load('services.yml');
$container->setParameter('config_path', __DIR__ . '/config');
$publisher = $container->get('publisher.demo');
$publisher->publish("test", "routing-key");
Exemplo n.º 25
0
<?php

require_once __DIR__ . '/../../vendor/autoload.php';
$container = new \Symfony\Component\DependencyInjection\ContainerBuilder();
$fileLocator = new \Symfony\Component\Config\FileLocator(__DIR__ . '/config');
$loader = new \Symfony\Component\DependencyInjection\Loader\YamlFileLoader($container, $fileLocator);
$loader->load('services.yml');
$container->setParameter('config_path', __DIR__ . '/config');
//var_dump($container->get('amqp.builder.factory')->releaseConnAndDeps());
$publisher = $container->get('amqp.builder.factory')->publisher('testExchange');
$message = 'test';
$publisher->publish($message, "example.test");
$message = 'Current date/time is ' . date('c');
$publisher->publish($message, "example.dateTime");
Exemplo n.º 26
0
 * (c) SquareProton <*****@*****.**>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
include __DIR__ . "/../../../bootstrap.php";
use Bond\Database\Exception\DatabaseAlreadyExistsException;
use Bond\Normality\DatabaseBuilder;
use Bond\Normality\Exception\AssetChangedException;
use Bond\Pg;
use Bond\Pg\Resource;
if (count($argv) != 2) {
    print "takes argument of asset directory/file\n";
    die(1);
}
$container = new \Symfony\Component\DependencyInjection\ContainerBuilder();
$configurator = new \Bond\Di\Configurator($container);
$configurator->load(__DIR__ . "/Di/ConnectionFactoryConfigurable.yml");
$container->compile();
$settingsDb = $container->get('connectionSettingsRW');
$databaseBuilder = new DatabaseBuilder();
try {
    $settingsDb = $databaseBuilder->create($settingsDb, '-');
} catch (DatabaseAlreadyExistsException $e) {
    $databaseBuilder->emptyDb($settingsDb);
}
// make a connection to the new database
$db = new Pg(new Resource($settingsDb));
try {
    $assets = $databaseBuilder->getSqlAssetsFromDirs($db, [$argv[1], __DIR__ . "/../../../../database/assets"], $assetsResolved);
    $databaseBuilder->resolveByDirs([$argv[1]], $assets, $assetsResolved);
Exemplo n.º 27
0
<?php

ini_set('display_errors', true);
include_once '../vendor/autoload.php';
$container = new Symfony\Component\DependencyInjection\ContainerBuilder();
$container->register('twig_loader', 'Twig_Loader_Filesystem')->addArgument('../src/Wizkunde/SAMLBase/Template/Twig');
$container->register('twig', 'Twig_Environment')->addArgument(new Symfony\Component\DependencyInjection\Reference('twig_loader'));
$container->register('guzzle_http', 'Guzzle\\Http\\Client');
$container->register('SigningCertificate', 'Wizkunde\\SAMLBase\\Certificate')->addMethodCall('setPassphrase', array('test1234'))->addMethodCall('setPublicKey', array('cert/example.crt', true))->addMethodCall('setPrivateKey', array('cert/example.pem', true));
$container->register('EncryptionCertificate', 'Wizkunde\\SAMLBase\\Certificate')->addMethodCall('setPassphrase', array('test1234'))->addMethodCall('setPublicKey', array('./cert/example.crt', true))->addMethodCall('setPrivateKey', array('./cert/example.pem', true));
$container->register('samlbase_idp_settings', 'Wizkunde\\SAMLBase\\Configuration\\Settings')->addMethodCall('setValues', array(array('NameID' => 'testNameId', 'Issuer' => 'http://saml.dev.wizkunde.nl/', 'MetadataExpirationTime' => 604800, 'SPReturnUrl' => 'http://return.wizkunde.nl/', 'ForceAuthn' => 'true', 'IsPassive' => 'false', 'NameIDFormat' => 'testNameId', 'ComparisonLevel' => 'exact', 'OptionalURLParameters' => array('source' => 'saml'))));
$container->register('samlbase_encryption', 'Wizkunde\\SAMLBase\\Security\\Encryption')->addMethodCall('setCertificate', array(new Symfony\Component\DependencyInjection\Reference('EncryptionCertificate')));
$container->register('samlbase_signature', 'Wizkunde\\SAMLBase\\Security\\Signature')->addMethodCall('setCertificate', array(new Symfony\Component\DependencyInjection\Reference('SigningCertificate')));
$container->register('samlbase_unique_id_generator', 'Wizkunde\\SAMLBase\\Configuration\\UniqueID');
$container->register('samlbase_timestamp_generator', 'Wizkunde\\SAMLBase\\Configuration\\Timestamp');
/**
 * Setup the Metadata resolve service
 */
$container->register('resolver', 'Wizkunde\\SAMLBase\\Metadata\\ResolveService')->addArgument(new Symfony\Component\DependencyInjection\Reference('guzzle_http'));
$container->register('samlbase_metadata', 'Wizkunde\\SAMLBase\\Metadata\\IDPMetadata');
/**
 * Resolve the metadata
 */
$metadata = $container->get('resolver')->resolve($container->get('samlbase_metadata'), 'http://idp.wizkunde.nl/simplesaml/saml2/idp/metadata.php');
// POST Binding
$container->register('samlbase_binding_post', 'Wizkunde\\SAMLBase\\Binding\\Post')->addMethodCall('setMetadata', array($metadata))->addMethodCall('setTwigService', array(new Symfony\Component\DependencyInjection\Reference('twig')))->addMethodCall('setUniqueIdService', array(new Symfony\Component\DependencyInjection\Reference('samlbase_unique_id_generator')))->addMethodCall('setTimestampService', array(new Symfony\Component\DependencyInjection\Reference('samlbase_timestamp_generator')))->addMethodCall('setSignatureService', array(new Symfony\Component\DependencyInjection\Reference('samlbase_signature')))->addMethodCall('setHttpService', array(new Symfony\Component\DependencyInjection\Reference('guzzle_http')));
// OR Redirect Binding
$container->register('samlbase_binding_redirect', 'Wizkunde\\SAMLBase\\Binding\\Redirect')->addMethodCall('setMetadata', array($metadata))->addMethodCall('setTwigService', array(new Symfony\Component\DependencyInjection\Reference('twig')))->addMethodCall('setUniqueIdService', array(new Symfony\Component\DependencyInjection\Reference('samlbase_unique_id_generator')))->addMethodCall('setTimestampService', array(new Symfony\Component\DependencyInjection\Reference('samlbase_timestamp_generator')))->addMethodCall('setSignatureService', array(new Symfony\Component\DependencyInjection\Reference('samlbase_signature')))->addMethodCall('setHttpService', array(new Symfony\Component\DependencyInjection\Reference('guzzle_http')));
$redirectUrl = $container->get('samlbase_binding_redirect')->setSettings($container->get('samlbase_idp_settings'))->request();
Exemplo n.º 28
0
<?php

require_once __DIR__ . '/../../vendor/autoload.php';
$container = new \Symfony\Component\DependencyInjection\ContainerBuilder();
$fileLocator = new \Symfony\Component\Config\FileLocator(__DIR__ . '/config');
$loader = new \Symfony\Component\DependencyInjection\Loader\YamlFileLoader($container, $fileLocator);
$loader->load('services.yml');
$container->setParameter('config_path', __DIR__ . '/config');
while (true) {
    $builder = $container->get('amqp.builder.factory');
    $connection = $builder->connection('live');
    $connection->disconnect();
    unset($connection);
}
Exemplo n.º 29
0
#!/usr/bin/php
<?php 
$config = ['git_urls' => ['https://github.com/symfony/DependencyInjection.git' => 'sf_dependency_injection/'], 'autoload_config' => ['sf_dependency_injection/' => 'Symfony\\Component\\DependencyInjection'], 'example' => function () {
    $sc = new Symfony\Component\DependencyInjection\ContainerBuilder();
    $sc->register('foo', '%foo.class%')->addArgument(new Symfony\Component\DependencyInjection\Reference('bar'));
    $sc->setParameter('foo.class', 'Foo');
    var_dump($sc);
}];
if ($return_config) {
    return $config;
}
require_once __DIR__ . '/_yf_autoloader.php';
new yf_autoloader($config);