public function getConstraints()
 {
     // evaluate any configured constraints
     $constraints = $this->owner->config()->get('constraints');
     $allConstraints = array();
     if (count($constraints)) {
         foreach ($constraints as $fieldName => $info) {
             // if we've only given one constraint, it'll be a string, so make it an array
             if (is_string($info)) {
                 $info = array($info);
             }
             foreach ($info as $constraintClass => $config) {
                 // allow plain classes, without arrays
                 if (is_numeric($constraintClass)) {
                     $constraintClass = $config;
                     $config = array();
                 }
                 if (!is_array($config)) {
                     parse_str($config, $arr);
                     $config = $arr;
                 }
                 if (!class_exists($constraintClass)) {
                     $constraintClass = 'SilverStripeAustralia\\Constraints\\Constraints\\' . $constraintClass;
                 }
                 $constraint = $this->injector->create($constraintClass, $this->owner, $fieldName, $config);
                 $allConstraints[] = $constraint;
             }
         }
     }
     return $allConstraints;
 }
 protected function getAuthenticator()
 {
     $injector = new Injector();
     $auth = new RESTfulAPI_TokenAuthenticator();
     $injector->inject($auth);
     return $auth;
 }
 protected function getSerializer()
 {
     $injector = new Injector();
     $serializer = new RESTfulAPI_BasicSerializer();
     $injector->inject($serializer);
     return $serializer;
 }
 protected function getQueryHandler()
 {
     $injector = new Injector();
     $qh = new RESTfulAPI_DefaultQueryHandler();
     $injector->inject($qh);
     return $qh;
 }
Пример #5
0
function injected()
{
    $injector = new Injector(array('ServiceA', 'ServiceB', 'ServiceC', 'ServiceD', 'ServiceE'));
    for ($i = 0; $i < ITERATIONS; $i++) {
        $obj = $injector->instantiate('MyObject');
        $obj->doSomething();
    }
}
Пример #6
0
 public function testProxyClass()
 {
     $config = array(array('class' => 'TestServiceForProxy', 'id' => 'TestServiceForProxy'), array('class' => 'TestAspectBean', 'id' => 'PreCallTest'), array('class' => 'TestAspectBean', 'id' => 'PostCallTest'), array('src' => dirname(dirname(dirname(__FILE__))) . '/services/AopProxyService.php', 'id' => 'TestService', 'properties' => array('proxied' => '#$TestServiceForProxy', 'beforeCall' => array('calculate' => '#$PreCallTest'), 'afterCall' => array('calculate' => '#$PostCallTest'))));
     $injector = new Injector($config);
     $test = $injector->get('TestService');
     $this->assertEqual('AopProxyService', get_class($test));
     $this->assertEqual(10, $test->calculate(5));
     $aspect1 = $injector->get('PreCallTest');
     $this->assertEqual(5, $aspect1->data['calculatepre']);
     $aspect2 = $injector->get('PostCallTest');
     $this->assertEqual(10, $aspect2->data['calculatepost']);
     $this->assertNotEqual($aspect1, $aspect2);
 }
 /**
  * Load the application context
  * @return ApplicationContext
  */
 protected function loadContext($config)
 {
     $loader = ContextLoaderFactory::getLoader($config);
     $context = $loader->load($config);
     $injector = new Injector($context);
     foreach ($context->getResources() as $resource) {
         $injector->inject($resource);
     }
     foreach ($context->getResources() as $resource) {
         if ($resource instanceof InitializingBean) {
             $resource->afterPropertiesSet();
         }
     }
     PiconApplication::get()->getContextLoadListener()->onContextLoaded($context);
 }
 /**
  * Creates a member in a group with the correct permissions.
  * Example: Given I am logged in with "ADMIN" permissions
  * 
  * @Given /^I am logged in with "([^"]*)" permissions$/
  */
 function iAmLoggedInWithPermissions($permCode)
 {
     if (!isset($this->cache_generatedMembers[$permCode])) {
         $group = \Group::get()->filter('Title', "{$permCode} group")->first();
         if (!$group) {
             $group = \Injector::inst()->create('Group');
         }
         $group->Title = "{$permCode} group";
         $group->write();
         $permission = \Injector::inst()->create('Permission');
         $permission->Code = $permCode;
         $permission->write();
         $group->Permissions()->add($permission);
         $member = \DataObject::get_one('Member', sprintf('"Email" = \'%s\'', "{$permCode}@example.org"));
         if (!$member) {
             $member = \Injector::inst()->create('Member');
         }
         // make sure any validation for password is skipped, since we're not testing complexity here
         $validator = \Member::password_validator();
         \Member::set_password_validator(null);
         $member->FirstName = $permCode;
         $member->Surname = "User";
         $member->Email = "{$permCode}@example.org";
         $member->PasswordEncryption = "none";
         $member->changePassword('Secret!123');
         $member->write();
         $group->Members()->add($member);
         \Member::set_password_validator($validator);
         $this->cache_generatedMembers[$permCode] = $member;
     }
     return new Step\Given(sprintf('I log in with "%s" and "%s"', "{$permCode}@example.org", 'Secret!123'));
 }
 public function connect()
 {
     if (!($member = Member::currentUser())) {
         /** @var stdClass $params */
         $params = $this->getAccessToken($this->request->getVar('code'));
         // member is not currently logged into SilverStripe. Look up
         // for a member with the UID which matches first.
         $member = Member::get()->filter(array("VkUID" => $params->user_id))->first();
         if (!$member) {
             // see if we have a match based on email. From a
             // security point of view, users have to confirm their
             // email address in facebook so doing a match up is fine
             $email = $params->email;
             if ($email) {
                 $member = Member::get()->filter(array('Email' => $email))->first();
             }
         }
         if (!$member) {
             $member = Injector::inst()->create('Member');
             $member->syncVkDetails($this->getUserInfo());
         }
     }
     $member->logIn(true);
     // redirect the user to the provided url, otherwise take them
     // back to the route of the website.
     if ($url = Session::get(VkControllerExtension::SESSION_REDIRECT_URL_FLAG)) {
         return $this->redirect($url);
     } else {
         return $this->redirect(Director::absoluteBaseUrl());
     }
 }
 /**
  * @return void
  */
 public function run()
 {
     try {
         $batch_size = 100;
         $init_time = time();
         $summit = null;
         if (isset($_GET['batch_size'])) {
             $batch_size = intval(trim(Convert::raw2sql($_GET['batch_size'])));
             echo sprintf('batch_size set to %s', $batch_size) . PHP_EOL;
         }
         if (isset($_GET['summit_id'])) {
             $summit = Summit::get()->byID(intval($_GET['summit_id']));
         }
         if (is_null($summit)) {
             throw new Exception('summit_id is not valid!');
         }
         $manager = Injector::inst()->get('SpeakerSecondBreakoutAnnouncementSenderManager');
         if (!$manager instanceof ISpeakerSecondBreakoutAnnouncementSenderManager) {
             return;
         }
         $processed = $manager->send($summit, $batch_size);
         $finish_time = time() - $init_time;
         echo 'processed records ' . $processed . ' - time elapsed : ' . $finish_time . ' seconds.';
     } catch (Exception $ex) {
         SS_Log::log($ex->getMessage(), SS_Log::ERR);
     }
 }
 /**
  * @test
  * @profile
  * @ignore(ignoreUntilFixed)
  */
 public function mockFactory()
 {
     $mockException = Mock_Factory::mock('Components\\Test_Exception', array('test/unit/case/mock', 'Mocked Exception.'));
     $mockExceptionDefault = Mock_Factory::mock('Components\\Test_Exception');
     $mockRunner = Mock_Factory::mock('Components\\Test_Runner');
     $mockListener = Mock_Factory::mock('Components\\Test_Listener');
     $mockListener->when('onInitialize')->doReturn(true);
     $mockListener->when('onExecute')->doReturn(true);
     $mockListener->when('onTerminate')->doNothing();
     assertTrue($mockListener->onExecute($mockRunner));
     assertTrue($mockListener->onInitialize($mockRunner));
     $mockLL->onTerminate($mockRunner);
     assertEquals('test/unit/case/mock', $mockException->getNamespace());
     assertEquals('Mocked Exception.', $mockException->getMessage());
     assertEquals('test/exception', $mockExceptionDefault->getNamespace());
     assertEquals('Test exception.', $mockExceptionDefault->getMessage());
     $mockBindingModule = Mock_Factory::mock('Components\\Binding_Module');
     $mockBindingModule->when('bind')->doAnswer(function (Binding_Module $self_, $type_) {
         echo "Bound {$type_}\r\n";
         return $self_->bind($type_);
     });
     $mockBindingModule->when('configure')->doAnswer(function (Binding_Module $self_) {
         $self_->bind('Components\\Test_Runner')->toInstance(Test_Runner::get());
         $self_->bind(Integer::TYPE)->toInstance(22)->named('boundInteger');
     });
     $injector = Injector::create($mockBindingModule);
     assertSame(Test_Runner::get(), $injector->resolveInstance('Components\\Test_Runner'));
     assertEquals(22, $injector->resolveInstance(Integer::TYPE, 'boundInteger'));
 }
 /**
  * @return MailingListAdapter
  */
 public static function adapter()
 {
     if (!isset(self::$adapter)) {
         self::$adapter = Injector::inst()->get(self::config()->default_adapter_class);
     }
     return self::$adapter;
 }
 /**
  * Get the appropriate {@link CatalogueProductController} or
  * {@link CatalogueProductController} for handling the relevent
  * object.
  *
  * @param $object Either Product or Category object
  * @param string $action
  * @return CatalogueController
  */
 protected static function controller_for($object, $action = null)
 {
     if ($object->class == 'CatalogueProduct') {
         $controller = "CatalogueProductController";
     } elseif ($object->class == 'CatalogueCategory') {
         $controller = "CatalogueCategoryController";
     } else {
         $ancestry = ClassInfo::ancestry($object->class);
         while ($class = array_pop($ancestry)) {
             if (class_exists($class . "_Controller")) {
                 break;
             }
         }
         // Find the controller we need, or revert to a default
         if ($class !== null) {
             $controller = "{$class}_Controller";
         } elseif (ClassInfo::baseDataClass($object->class) == "CatalogueProduct") {
             $controller = "CatalogueProductController";
         } elseif (ClassInfo::baseDataClass($object->class) == "CatalogueCategory") {
             $controller = "CatalogueCategoryController";
         }
     }
     if ($action && class_exists($controller . '_' . ucfirst($action))) {
         $controller = $controller . '_' . ucfirst($action);
     }
     return class_exists($controller) ? Injector::inst()->create($controller, $object) : $object;
 }
 /**
  * @param $methods
  * @param null $responseWill
  * @return mixed
  */
 protected function createMockYouTubeService($methods, $responseWill = null)
 {
     if (!is_array($methods)) {
         $methods = [$methods];
     }
     if (!$responseWill) {
         $responseWill = $this->returnSelf();
     }
     $methodMap = [];
     foreach ($methods as $methodName => $callback) {
         if (is_numeric($methodName)) {
             $methodName = $callback;
         }
         $expects = is_callable($callback) ? $callback($this) : $this->any();
         $methodMap[$methodName] = $expects;
     }
     $mockResponse = $this->getMockBuilder('GuzzleHttp\\Stream\\Stream')->setMethods(['getBody', 'getContents'])->disableOriginalConstructor()->getMock();
     $mockResponse->expects($this->any())->method('getBody')->will($this->returnSelf());
     $mockResponse->expects($this->any())->method('getContents')->will($responseWill);
     $mockService = $this->getMockBuilder('SummitVideoYouTubeService')->setConstructorArgs([Injector::inst()->get('SummitVideoHTTPClient')])->setMethods(array_keys($methodMap))->getMock();
     foreach ($methodMap as $methodName => $expects) {
         $mockService->expects($expects)->method($methodName)->will($this->returnValue($mockResponse));
     }
     return $mockService;
 }
Пример #15
0
 static function add_to_class($class, $extensionClass, $args = null)
 {
     if (method_exists($class, 'extraDBFields')) {
         $extraStaticsMethod = 'extraDBFields';
     } else {
         $extraStaticsMethod = 'extraStatics';
     }
     $statics = Injector::inst()->get($extensionClass, true, $args)->{$extraStaticsMethod}($class, $extensionClass);
     if ($statics) {
         Deprecation::notice('3.1.0', "{$extraStaticsMethod} deprecated. Just define statics on your extension, or use add_to_class");
         // TODO: This currently makes extraStatics the MOST IMPORTANT config layer, not the least
         foreach (self::$extendable_statics as $key => $merge) {
             if (isset($statics[$key])) {
                 if (!$merge) {
                     Config::inst()->remove($class, $key);
                 }
                 Config::inst()->update($class, $key, $statics[$key]);
             }
         }
         // TODO - remove this
         DataObject::$cache_has_own_table[$class] = null;
         DataObject::$cache_has_own_table_field[$class] = null;
     }
     parent::add_to_class($class, $extensionClass, $args);
 }
 /**
  * This should be updateCMSFields and configured to be called last but configuration
  * priority does not seem to work to force this to be the last loaded/called extension.
  *
  * For now will call via extend.manualUpdate with the field list in ArtisanModel.getCMSFields
  *
  * @param FieldList $fields
  */
 public function manualUpdateCMSFields(FieldList $fields)
 {
     //        $formFields = $fields->dataFields();
     $formFields = $fields->VisibleFields();
     $selectorFieldName = parent::get_config_setting('selector_field_name');
     $hiddenCSSClass = parent::get_config_setting('hidden_css_class');
     $provider = Injector::inst()->get('AdaptableFormMetaDataProvider');
     $defaultFieldNames = $provider->getDefaultFieldNames();
     // keep track of fields we have encountered in the spec, other fields will be hidden,
     // we can initialise this to defaultFieldNames as we don't want to hide these ever
     $handled = array_combine($defaultFieldNames, $defaultFieldNames);
     // we want to get the form so we can remove fields later
     $form = null;
     $metaData = $provider->getMetaData();
     // the master list of content types by field name
     $this->contentTypes = [];
     foreach ($metaData as $contentType => $fieldSpec) {
         if (isset($fieldSpec['FormFields'])) {
             $fieldDefinitions = $fieldSpec['FormFields'];
             $specFields = array_merge($fieldDefinitions, $defaultFieldNames);
             $this->processFieldList($formFields, $contentType, $selectorFieldName, $specFields, $defaultFieldNames, $handled);
         }
     }
     $this->hideUnhandled($formFields, $handled, $hiddenCSSClass);
 }
 /**
  * Will redirect the user directly to the IdP login endpoint if:
  *
  * 1) the 'SAMLAuthenticator' is the default authenticator
  * 2) there isn't a GET param showloginform set to 1
  * 3) the member is not currently logged in
  * 4) there are no form messages (errors or notices)
  *
  * @return void
  */
 public function onBeforeSecurityLogin()
 {
     if (Authenticator::get_default_authenticator() != 'SAMLAuthenticator') {
         return;
     }
     // by going to the URL Security/login?showloginform=1 we bypass the auto sign on
     if ($this->owner->request->getVar('showloginform') == 1) {
         return;
     }
     // if member is already logged in, don't auto-sign-on, this is most likely because
     // of unsufficient permissions.
     $member = Member::currentUser();
     if ($member && $member->exists()) {
         return;
     }
     // if there are form messages, don't auto-sign-on, this is most likely because of
     // login errors / failures or other notices.
     if (Session::get('FormInfo')) {
         // since FormInfo can be a "nulled" array, we have to check
         foreach (Session::get('FormInfo') as $form => $info) {
             foreach ($info as $name => $value) {
                 if ($value !== null) {
                     return;
                 }
             }
         }
     }
     $backURL = Session::get('BackURL');
     if ($this->owner->request->getVar('BackURL')) {
         $backURL = $this->owner->request->getVar('BackURL');
     }
     $authenticator = Injector::inst()->create('SAMLAuthenticator');
     $authenticator->authenticate(array("BackURL" => $backURL));
 }
 /**
  * @param IRSVPTemplate $template
  * @param IRSVP $rsvp
  * @param ISummitEvent $event
  * @param string $form_name
  * @return BootstrapForm|PresentationSpeaker
  */
 public function build(IRSVPTemplate $template, IRSVP $rsvp, ISummitEvent $event, $form_name = 'RSVPForm')
 {
     $fields = new FieldList();
     foreach ($template->getQuestions() as $q) {
         $type = $q->Type();
         $builder_class = $type . 'UIBuilder';
         // @IRSVPQuestionTemplateUIBuilder
         $builder = Injector::inst()->create($builder_class);
         $answer = $rsvp ? $rsvp->findAnswerByQuestion($q) : null;
         $field = $builder->build($rsvp, $q, $answer);
         $fields->add($field);
     }
     $validator = null;
     if ($rsvp) {
         $fields->add(new HiddenField('rsvp_id', 'rsvp_id', $rsvp->getIdentifier()));
     }
     $fields->add(new HiddenField('event_id', 'event_id', $event->getIdentifier()));
     $fields->add(new HiddenField('summit_id', 'summit_id', $event->Summit()->getIdentifier()));
     $fields->add(new HiddenField('seat_type', 'seat_type', $event->getCurrentRSVPSubmissionSeatType()));
     $fields->add(new LiteralField('hr', '<hr>'));
     $actions = new FieldList(FormAction::create('submit_rsvp')->setTitle('Send RSVP')->addExtraClass('rsvp_submit'));
     $form = new BootstrapForm(Controller::curr(), $form_name . '_' . $event->getIdentifier(), $fields, $actions, $validator);
     $form->setAttribute('class', 'rsvp_form');
     return $form;
 }
 /**
  * Entry point for message queue
  *
  * @param int $batchSize
  * @param string $taskName
  * @param array|string|null $classes
  */
 public static function run_reindex($batchSize, $taskName, $classes = null)
 {
     // @todo Logger for message queue?
     $logger = Injector::inst()->createWithArgs('Monolog\\Logger', array(strtolower(get_class())));
     $inst = Injector::inst()->get(get_class());
     $inst->runReindex($logger, $batchSize, $taskName, $classes);
 }
Пример #20
0
 public static function authenticate($email, $password)
 {
     $authenticator = \Injector::inst()->get('ApiMemberAuthenticator');
     if ($user = $authenticator->authenticate(['Password' => $password, 'Email' => $email])) {
         return self::createSession($user);
     }
 }
Пример #21
0
 public function __construct()
 {
     $this->session = Injector::inst()->create('Session', array());
     $this->controller = new Controller();
     $this->controller->setSession($this->session);
     $this->controller->pushCurrent();
 }
 /**
  * @return FixtureFactory
  */
 public function getFixtureFactory()
 {
     if (!$this->fixtureFactory) {
         $this->fixtureFactory = \Injector::inst()->create('BehatFixtureFactory');
     }
     return $this->fixtureFactory;
 }
 /**
  * @return DynamicTranslationAdapter
  */
 public static function get_translation_adapter()
 {
     if (!self::$translation_adapter) {
         self::$translation_adapter = Injector::inst()->get('DynamicTranslationAdapter');
     }
     return self::$translation_adapter;
 }
 public function run($request)
 {
     $service = Injector::inst()->create('GoogleAnalyticsUpgradeService');
     $service->log("Upgrading googleanalytics module");
     $service->setQuiet(false)->run();
     $service->log("Done");
 }
 /**
  * @return AjaxHTTPResponse
  */
 public function getAjaxResponse()
 {
     if (!isset($this->ajaxResponse)) {
         $this->ajaxResponse = Injector::inst()->create('AjaxHTTPResponse', $this->owner->getRequest());
     }
     return $this->ajaxResponse;
 }
 public function updateEnabled(&$enabled)
 {
     if ($enabled && Session::get("loggedInAs")) {
         $this->checkAndConnectDB();
         $enabled = !Injector::inst()->create('LeftAndMain')->canView();
     }
 }
 /**
  * Performs the login, but will also create and sync the Member record on-the-fly, if not found.
  *
  * @param array $data
  * @param Form $form
  * @return bool|Member|void
  * @throws SS_HTTPResponse_Exception
  */
 public static function authenticate($data, Form $form = null)
 {
     $service = Injector::inst()->get('LDAPService');
     $result = $service->authenticate($data['Username'], $data['Password']);
     $success = $result['success'] === true;
     if (!$success) {
         if ($form) {
             $form->sessionMessage($result['message'], 'bad');
         }
         return;
     }
     $data = $service->getUserByUsername($result['identity']);
     if (!$data) {
         if ($form) {
             $form->sessionMessage(_t('LDAPAuthenticator.PROBLEMFINDINGDATA', 'There was a problem retrieving your user data'), 'bad');
         }
         return;
     }
     // LDAPMemberExtension::memberLoggedIn() will update any other AD attributes mapped to Member fields
     $member = Member::get()->filter('GUID', $data['objectguid'])->limit(1)->first();
     if (!($member && $member->exists())) {
         $member = new Member();
         $member->GUID = $data['objectguid'];
         $member->write();
     }
     Session::clear('BackURL');
     return $member;
 }
 public function fire()
 {
     increase_memory_limit_to();
     increase_time_limit_to();
     /** @var i18nTextCollector $collector */
     $collector = i18nTextCollector::create($this->option('locale'));
     if (!$this->option('locale')) {
         $this->info('Starting text collection. No Locale specified');
     } else {
         $this->info('Starting text collection for: ' . $this->option('locale'));
     }
     $merge = $this->getIsMerge();
     if ($merge) {
         $this->info('New strings will be merged with existing strings');
     }
     // Custom writer
     $writerName = $this->option('writer');
     if ($writerName) {
         $writer = Injector::inst()->get($writerName);
         $collector->setWriter($writer);
         $this->info('Set collector writer to: ' . $writer);
     }
     // Get restrictions
     $restrictModules = $this->option('module') ? explode(',', $this->option('module')) : null;
     $this->info('Collecting in modules: ' . $this->option('module'));
     // hack untill we have something better
     ob_start();
     $collector->run($restrictModules, $merge);
     $this->warn(ob_get_contents());
     ob_get_clean();
     $this->info(__CLASS__ . ' completed!');
 }
 /**
  * This routine simulates what would happen when a object is constructed
  * @param string $data
  * @return void
  */
 public function unserialize($data)
 {
     $injector = \Injector::inst();
     $extraData = null;
     if (empty(self::$objectConstructorReflectionMethods[__CLASS__])) {
         self::$objectConstructorReflectionMethods[__CLASS__] = new \ReflectionMethod(__CLASS__, '__construct');
     }
     if (empty(self::$classConfigs[__CLASS__])) {
         self::$classConfigs[__CLASS__] = $injector->getConfigLocator()->locateConfigFor(__CLASS__);
     }
     if ($this instanceof ExtraDataInterface) {
         $unserialized = \Heystack\Core\unserialize($data);
         self::$objectConstructorReflectionMethods[__CLASS__]->invoke($this, $unserialized[0]);
         $extraData = $unserialized[1];
     } else {
         self::$objectConstructorReflectionMethods[__CLASS__]->invoke($this, \Heystack\Core\unserialize($data));
     }
     // Ensure that the spec is loaded for the class
     if (self::$classConfigs[__CLASS__]) {
         $injector->load([__CLASS__ => self::$classConfigs[__CLASS__]]);
     }
     $injector->inject($this, __CLASS__);
     if ($extraData) {
         $this->setExtraData($extraData);
     }
 }
 public function updateItemEditForm($form)
 {
     if ($id = $this->owner->request->getVar('ID')) {
         Injector::inst()->get("CMSMain")->setCurrentPageID($id);
         $form->Fields()->push(new HiddenField('ID', '', $id));
     }
 }