Esempio n. 1
0
 public function onKernelException(GetResponseForExceptionEvent $event)
 {
     $exception = $event->getException();
     $request = $event->getRequest();
     $this->logException($exception, sprintf('Uncaught PHP Exception %s: "%s" at %s line %s', get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine()));
     $attributes = array('_controller' => $this->controller, 'exception' => FlattenException::create($exception), 'logger' => $this->logger instanceof DebugLoggerInterface ? $this->logger : null, 'format' => $request->getRequestFormat());
     $request = $request->duplicate(null, null, $attributes);
     $request->setMethod('GET');
     try {
         $response = $event->getKernel()->handle($request, HttpKernelInterface::SUB_REQUEST, false);
     } catch (\Exception $e) {
         $this->logException($e, sprintf('Exception thrown when handling an exception (%s: %s at %s line %s)', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()), false);
         $wrapper = $e;
         while ($prev = $wrapper->getPrevious()) {
             if ($exception === ($wrapper = $prev)) {
                 throw $e;
             }
         }
         $prev = new \ReflectionProperty('Exception', 'previous');
         $prev->setAccessible(true);
         $prev->setValue($wrapper, $exception);
         throw $e;
     }
     $event->setResponse($response);
 }
Esempio n. 2
0
 /**
  * Test factory method
  */
 public function testValue()
 {
     $typecast = TypeCast::value('abc123');
     $refl = new \ReflectionProperty('Jasny\\TypeCast', 'value');
     $refl->setAccessible(true);
     $this->assertSame('abc123', $refl->getValue($typecast));
 }
Esempio n. 3
0
 public function __call($name, $args)
 {
     $class = get_class($this);
     if ($name === '') {
         throw new MemberAccessException("Call to class '{$class}' method without name.");
     }
     if (preg_match('#^on[A-Z]#', $name)) {
         $rp = new ReflectionProperty($class, $name);
         if ($rp->isPublic() && !$rp->isStatic()) {
             $list = $this->{$name};
             if (is_array($list) || $list instanceof Traversable) {
                 foreach ($list as $handler) {
                     if (is_object($handler)) {
                         call_user_func_array(array($handler, '__invoke'), $args);
                     } else {
                         call_user_func_array($handler, $args);
                     }
                 }
             }
             return NULL;
         }
     }
     if ($cb = self::extensionMethod("{$class}::{$name}")) {
         array_unshift($args, $this);
         return call_user_func_array($cb, $args);
     }
     throw new MemberAccessException("Call to undefined method {$class}::{$name}().");
 }
Esempio n. 4
0
 /**
  * Force connection setter injection on setup model using reflection
  * 
  * @param $setup
  * @param $connection
  */
 protected function _setConnectionOnInstaller($setup, $connection)
 {
     $prop = new ReflectionProperty($setup, '_conn');
     $prop->setAccessible(true);
     $prop->setValue($setup, $connection);
     $prop->setAccessible(false);
 }
 /**
  * Test for ExportCodegen::setProperties
  *
  * @return void
  */
 public function testSetProperties()
 {
     $method = new ReflectionMethod('ExportCodegen', 'setProperties');
     $method->setAccessible(true);
     $method->invoke($this->object, null);
     $attrProperties = new ReflectionProperty('ExportCodegen', 'properties');
     $attrProperties->setAccessible(true);
     $properties = $attrProperties->getValue($this->object);
     $this->assertInstanceOf('ExportPluginProperties', $properties);
     $this->assertEquals('CodeGen', $properties->getText());
     $this->assertEquals('cs', $properties->getExtension());
     $this->assertEquals('text/cs', $properties->getMimeType());
     $this->assertEquals('Options', $properties->getOptionsText());
     $options = $properties->getOptions();
     $this->assertInstanceOf('OptionsPropertyRootGroup', $options);
     $this->assertEquals('Format Specific Options', $options->getName());
     $generalOptionsArray = $options->getProperties();
     $generalOptions = $generalOptionsArray[0];
     $this->assertInstanceOf('OptionsPropertyMainGroup', $generalOptions);
     $this->assertEquals('general_opts', $generalOptions->getName());
     $generalProperties = $generalOptions->getProperties();
     $hidden = $generalProperties[0];
     $this->assertInstanceOf('HiddenPropertyItem', $hidden);
     $this->assertEquals('structure_or_data', $hidden->getName());
     $select = $generalProperties[1];
     $this->assertInstanceOf('SelectPropertyItem', $select);
     $this->assertEquals('format', $select->getName());
     $this->assertEquals('Format:', $select->getText());
     $this->assertEquals(array("NHibernate C# DO", "NHibernate XML"), $select->getValues());
 }
Esempio n. 6
0
 public function initialize($object)
 {
     $reflectionClass = new ReflectionClass($object);
     $reader = new Phake_Annotation_Reader($reflectionClass);
     if ($this->useDoctrineParser()) {
         $parser = new \Doctrine\Common\Annotations\PhpParser();
     }
     $properties = $reader->getPropertiesWithAnnotation('Mock');
     foreach ($properties as $property) {
         $annotations = $reader->getPropertyAnnotations($property);
         if ($annotations['Mock'] !== true) {
             $mockedClass = $annotations['Mock'];
         } else {
             $mockedClass = $annotations['var'];
         }
         if (isset($parser)) {
             // Ignore it if the class start with a backslash
             if (substr($mockedClass, 0, 1) !== '\\') {
                 $useStatements = $parser->parseClass($reflectionClass);
                 $key = strtolower($mockedClass);
                 if (array_key_exists($key, $useStatements)) {
                     $mockedClass = $useStatements[$key];
                 }
             }
         }
         $reflProp = new ReflectionProperty(get_class($object), $property);
         $reflProp->setAccessible(true);
         $reflProp->setValue($object, Phake::mock($mockedClass));
     }
 }
 /**
  * Constructor.
  *
  * @param RepositoryInterface $repository PathRepository object
  */
 public function __construct(RepositoryInterface $repository)
 {
     $reflection = new \ReflectionProperty(get_class($repository), 'url');
     $reflection->setAccessible(true);
     $this->url = $reflection->getValue($repository);
     #$repository->url;
 }
    public function testIndex()
    {
        $logger = $this->getMock('Psr\\Log\\LoggerInterface');
        $logger->expects($this->once())->method('info');
        $controller = new Controller($logger);
        $prop = new \ReflectionProperty(__NAMESPACE__ . '\\Controller', 'response');
        $prop->setAccessible(true);
        $prop->setValue($controller, new \SS_HTTPResponse());
        $req = new \SS_HTTPRequest('GET', '/');
        $req->setBody(<<<JSON
{
  "csp-report": {
    "document-uri": "http://example.com/signup.html",
    "referrer": "",
    "blocked-uri": "http://example.com/css/style.css",
    "violated-directive": "style-src cdn.example.com",
    "original-policy": "default-src 'none'; style-src cdn.example.com; report-uri /_/csp-reports"
  }
}
JSON
);
        $response = $controller->index($req);
        $this->assertEquals(204, $response->getStatusCode());
        $this->assertEquals('', $response->getBody());
    }
Esempio n. 9
0
 /**
  * Initialize list of scalar properties by response
  *
  * @param \SimpleXMLElement $apiResponse
  * @param array $properties
  * @throws \Exception
  */
 protected function _initScalarProperties($apiResponse, array $properties)
 {
     foreach ($properties as $property) {
         if (is_array($property)) {
             $classPropertyName = current($property);
             $value = $apiResponse->{key($property)};
         } else {
             $classPropertyName = $this->_underToCamel(str_replace('-', '_', $property));
             $value = $apiResponse->{$property};
         }
         $reflectionProperty = new \ReflectionProperty($this, $classPropertyName);
         $docBlock = $reflectionProperty->getDocComment();
         $propertyType = preg_replace('/^.+ @var ([a-z]+) .+$/', '\\1', $docBlock);
         if ('string' == $propertyType) {
             $value = (string) $value;
         } else {
             if ('integer' == $propertyType) {
                 $value = (int) $value;
             } else {
                 if ('boolean' == $propertyType) {
                     $value = in_array((string) $value, ['true', 'on', 'enabled']);
                 } else {
                     throw new \Exception("Unknown property type '{$propertyType}'.");
                 }
             }
         }
         $this->{$classPropertyName} = $value;
     }
 }
Esempio n. 10
0
 protected function actionBucketList(WURFL_Utils_CLI_Argument $arg)
 {
     $wurfl_service = new ReflectionProperty('WURFL_WURFLManager', '_wurflService');
     $wurfl_service->setAccessible(true);
     $service = $wurfl_service->getValue($this->wurfl);
     $wurfl_ua_chain = new ReflectionProperty('WURFL_WURFLService', '_userAgentHandlerChain');
     $wurfl_ua_chain->setAccessible(true);
     $ua_chain = $wurfl_ua_chain->getValue($service);
     echo 'PHP API v' . WURFL_Constants::API_VERSION . ' for ' . $this->wurfl->getWURFLInfo()->version . PHP_EOL;
     echo "Bucket\tDeviceId\tNormalizedUserAgent\tOriginaUserAgent" . PHP_EOL;
     $ordered_buckets = [];
     foreach ($ua_chain->getHandlers() as $userAgentHandler) {
         $ordered_buckets[$this->formatBucketName($userAgentHandler->getName())] = $userAgentHandler;
     }
     ksort($ordered_buckets);
     foreach ($ordered_buckets as $bucket => $userAgentHandler) {
         /**
          * @see WURFL_Handlers_Handler::getUserAgentsWithDeviceId()
          */
         $current = $userAgentHandler->getUserAgentsWithDeviceId();
         if ($current) {
             $sorted = array_flip($current);
             ksort($sorted);
             foreach ($sorted as $device_id => $normalized_ua) {
                 $device = $this->wurfl->getDevice($device_id);
                 echo $bucket . "\t" . $device_id . "\t" . $normalized_ua . "\t" . $device->userAgent . PHP_EOL;
             }
         } else {
             echo $bucket . "\t" . 'EMPTY' . "\t" . 'EMPTY' . "\t" . 'EMPTY' . PHP_EOL;
         }
     }
 }
Esempio n. 11
0
 public function __construct(InputInterface $input, OutputInterface $output)
 {
     parent::__construct($input, $output);
     $ref = new \ReflectionProperty(get_parent_class($this), 'lineLength');
     $ref->setAccessible(true);
     $ref->setValue($this, 120);
 }
Esempio n. 12
0
 /**
  * @param \ReflectionProperty $property
  * @return int
  */
 public static function getPropertyLine(\ReflectionProperty $property)
 {
     $class = $property->getDeclaringClass();
     $context = 'file';
     $contextBrackets = 0;
     foreach (token_get_all(file_get_contents($class->getFileName())) as $token) {
         if ($token === '{') {
             $contextBrackets += 1;
         } elseif ($token === '}') {
             $contextBrackets -= 1;
         }
         if (!is_array($token)) {
             continue;
         }
         if ($token[0] === T_CLASS) {
             $context = 'class';
             $contextBrackets = 0;
         } elseif ($context === 'class' && $contextBrackets === 1 && $token[0] === T_VARIABLE) {
             if ($token[1] === '$' . $property->getName()) {
                 return $token[2];
             }
         }
     }
     return NULL;
 }
Esempio n. 13
0
 /**
  * @param bool $canReturnToStock
  * @param bool $manageStock
  * @param bool $result
  * @dataProvider canReturnItemsToStockDataProvider
  */
 public function testCanReturnItemsToStock($canReturnToStock, $manageStock, $result)
 {
     $productId = 7;
     $property = new \ReflectionProperty($this->items, '_canReturnToStock');
     $property->setAccessible(true);
     $this->assertNull($property->getValue($this->items));
     $this->stockConfiguration->expects($this->once())->method('canSubtractQty')->will($this->returnValue($canReturnToStock));
     if ($canReturnToStock) {
         $orderItem = $this->getMock('Magento\\Sales\\Model\\Order\\Item', ['getProductId', '__wakeup', 'getStore'], [], '', false);
         $store = $this->getMock('Magento\\Store\\Model\\Store', ['getWebsiteId'], [], '', false);
         $store->expects($this->once())->method('getWebsiteId')->will($this->returnValue(10));
         $orderItem->expects($this->any())->method('getStore')->will($this->returnValue($store));
         $orderItem->expects($this->once())->method('getProductId')->will($this->returnValue($productId));
         $creditMemoItem = $this->getMock('Magento\\Sales\\Model\\Order\\Creditmemo\\Item', ['setCanReturnToStock', 'getOrderItem', '__wakeup'], [], '', false);
         $creditMemo = $this->getMock('Magento\\Sales\\Model\\Order\\Creditmemo', [], [], '', false);
         $creditMemo->expects($this->once())->method('getAllItems')->will($this->returnValue([$creditMemoItem]));
         $creditMemoItem->expects($this->any())->method('getOrderItem')->will($this->returnValue($orderItem));
         $this->stockItemMock->expects($this->once())->method('getManageStock')->will($this->returnValue($manageStock));
         $creditMemoItem->expects($this->once())->method('setCanReturnToStock')->with($this->equalTo($manageStock))->will($this->returnSelf());
         $order = $this->getMock('Magento\\Sales\\Model\\Order', ['setCanReturnToStock', '__wakeup'], [], '', false);
         $order->expects($this->once())->method('setCanReturnToStock')->with($this->equalTo($manageStock))->will($this->returnSelf());
         $creditMemo->expects($this->once())->method('getOrder')->will($this->returnValue($order));
         $this->registryMock->expects($this->any())->method('registry')->with('current_creditmemo')->will($this->returnValue($creditMemo));
     }
     $this->assertSame($result, $this->items->canReturnItemsToStock());
     $this->assertSame($result, $property->getValue($this->items));
     // lazy load test
     $this->assertSame($result, $this->items->canReturnItemsToStock());
 }
Esempio n. 14
0
 protected function openPresenter($fqa)
 {
     /** @var IntegrationTestCase|PresenterRunner $this */
     $sl = $this->getContainer();
     //insert fake HTTP Request for Presenter - for presenter->link() etc.
     $params = $sl->getParameters();
     $this->fakeUrl = new Nette\Http\UrlScript(isset($params['console']['url']) ? $params['console']['url'] : 'localhost');
     $sl->removeService('httpRequest');
     $sl->addService('httpRequest', new HttpRequest($this->fakeUrl, NULL, [], [], [], [], PHP_SAPI, '127.0.0.1', '127.0.0.1'));
     /** @var Nette\Application\IPresenterFactory $presenterFactory */
     $presenterFactory = $sl->getByType('Nette\\Application\\IPresenterFactory');
     $name = substr($fqa, 0, $namePos = strrpos($fqa, ':'));
     $class = $presenterFactory->getPresenterClass($name);
     if (!class_exists($overriddenPresenter = 'DamejidloTests\\' . $class)) {
         $classPos = strrpos($class, '\\');
         eval('namespace DamejidloTests\\' . substr($class, 0, $classPos) . '; class ' . substr($class, $classPos + 1) . ' extends \\' . $class . ' { ' . 'protected function startup() { if ($this->getParameter("__terminate") == TRUE) { $this->terminate(); } parent::startup(); } ' . 'public static function getReflection() { return parent::getReflection()->getParentClass(); } ' . '}');
     }
     $this->presenter = $sl->createInstance($overriddenPresenter);
     $sl->callInjects($this->presenter);
     $app = $this->getService('Nette\\Application\\Application');
     $appRefl = new \ReflectionProperty($app, 'presenter');
     $appRefl->setAccessible(TRUE);
     $appRefl->setValue($app, $this->presenter);
     $this->presenter->autoCanonicalize = FALSE;
     $this->presenter->run(new Nette\Application\Request($name, 'GET', ['action' => substr($fqa, $namePos + 1) ?: 'default', '__terminate' => TRUE]));
 }
Esempio n. 15
0
 /**
  * @param \ReflectionProperty $accessedProperty
  * @param string              $nameSuffix
  */
 public function __construct(\ReflectionProperty $accessedProperty, $nameSuffix)
 {
     $this->accessedProperty = $accessedProperty;
     $originalName = $accessedProperty->getName();
     $name = UniqueIdentifierGenerator::getIdentifier($originalName . $nameSuffix);
     parent::__construct(Class_::MODIFIER_PRIVATE, [new PropertyProperty($name)]);
 }
Esempio n. 16
0
 private function enableOpenSSL()
 {
     $ref = new \ReflectionProperty('Bitpay\\Util\\SecureRandom', 'hasOpenSSL');
     $ref->setAccessible(true);
     $ref->setValue(null);
     $ref->setAccessible(false);
 }
Esempio n. 17
0
 /**
  * setup mocks for all functions
  */
 public function setUp()
 {
     $this->_objectHelper = new \Magento\TestFramework\Helper\ObjectManager($this);
     $this->_orderMock = $this->getMockBuilder('\\Magento\\Sales\\Model\\Order')->disableOriginalConstructor()->setMethods(array('__wakeup', 'getRealOrderId'))->getMock();
     $this->_messageMock = $this->getMockBuilder('\\Magento\\Framework\\Message')->disableOriginalConstructor()->setMethods(array('addError'))->getMock();
     $titleMock = $this->getMock('\\Magento\\Framework\\App\\Action\\Title', array('__wakeup', 'add'), array(), '', false);
     $viewMock = $this->getMockForAbstractClass('\\Magento\\Framework\\App\\ViewInterface');
     /**
      * @TODO:
      *  - Methods of object under test MUST NOT be mocked
      *  - Protected properties MUST NOT be set from outside, inject via context passed to constructor instead
      */
     $this->_controllerMock = $this->getMockBuilder('\\Magento\\Sales\\Controller\\Adminhtml\\Order\\View')->disableOriginalConstructor()->setMethods(array('__wakeup', '_initOrder', '_initAction', '__', 'renderLayout', '_redirect'))->getMock();
     $this->_controllerMock->expects($this->any())->method('__')->will($this->returnArgument(0));
     $reflectionProperty = new \ReflectionProperty('\\Magento\\Sales\\Controller\\Adminhtml\\Order', '_title');
     $reflectionProperty->setAccessible(true);
     $reflectionProperty->setValue($this->_controllerMock, $titleMock);
     $reflectionProperty->setAccessible(false);
     $reflectionProperty = new \ReflectionProperty('\\Magento\\Sales\\Controller\\Adminhtml\\Order', '_view');
     $reflectionProperty->setAccessible(true);
     $reflectionProperty->setValue($this->_controllerMock, $viewMock);
     $reflectionProperty->setAccessible(false);
     $reflectionProperty = new \ReflectionProperty('\\Magento\\Sales\\Controller\\Adminhtml\\Order', 'messageManager');
     $reflectionProperty->setAccessible(true);
     $reflectionProperty->setValue($this->_controllerMock, $this->_messageMock);
     $reflectionProperty->setAccessible(false);
 }
 public function tearDown()
 {
     $property = new \ReflectionProperty('\\Magento\\Setup\\Module\\I18n\\ServiceLocator', '_dictionaryGenerator');
     $property->setAccessible(true);
     $property->setValue(null);
     $property->setAccessible(false);
 }
Esempio n. 19
0
 /**
  * @dataProvider dataConstructor
  */
 public function testConstructor($options, $expected)
 {
     $mock = $this->getObject($options);
     $reflectedProperty = new \ReflectionProperty(get_class($mock), 'options');
     $reflectedProperty->setAccessible(true);
     $this->assertEquals($expected, $reflectedProperty->getValue($mock));
 }
 public function __construct(\ReflectionProperty $property)
 {
     $this->_property = $property;
     $comment = $property->getDocComment();
     $comment = new DocBloc($comment);
     $this->_annotations = $comment->getAnnotations();
 }
 /**
  * Constructs the exception.
  * @link http://php.net/manual/en/errorexception.construct.php
  * @param $message [optional]
  * @param $code [optional]
  * @param $severity [optional]
  * @param $filename [optional]
  * @param $lineno [optional]
  * @param $previous [optional]
  */
 public function __construct($message = '', $code = 0, $severity = 1, $filename = __FILE__, $lineno = __LINE__, \Exception $previous = null)
 {
     parent::__construct($message, $code, $severity, $filename, $lineno, $previous);
     if (function_exists('xdebug_get_function_stack')) {
         $trace = array_slice(array_reverse(xdebug_get_function_stack()), 3, -1);
         foreach ($trace as &$frame) {
             if (!isset($frame['function'])) {
                 $frame['function'] = 'unknown';
             }
             // XDebug < 2.1.1: http://bugs.xdebug.org/view.php?id=695
             if (!isset($frame['type']) || $frame['type'] === 'static') {
                 $frame['type'] = '::';
             } elseif ($frame['type'] === 'dynamic') {
                 $frame['type'] = '->';
             }
             // XDebug has a different key name
             if (isset($frame['params']) && !isset($frame['args'])) {
                 $frame['args'] = $frame['params'];
             }
         }
         $ref = new \ReflectionProperty('Exception', 'trace');
         $ref->setAccessible(true);
         $ref->setValue($this, $trace);
     }
 }
Esempio n. 22
0
 public function __construct()
 {
     $arguments = func_get_args();
     $count = count($arguments);
     // get reflection from class or class/method
     // (depends on constructor arguments)
     if ($count === 0) {
         throw new \Exception("No zero argument constructor allowed");
     } else {
         if ($count === 1) {
             $reflection = new \ReflectionClass($arguments[0]);
         } else {
             $type = $count === 3 ? $arguments[2] : "method";
             if ($type === "method") {
                 $reflection = new \ReflectionMethod($arguments[0], $arguments[1]);
             } else {
                 if ($type === "property") {
                     $reflection = new \ReflectionProperty($arguments[0], $arguments[1]);
                 }
             }
         }
     }
     $this->rawDocBlock = $reflection->getDocComment();
     $this->parameters = array();
 }
 /**
  * @param callable $callback
  */
 public function __construct(callable $callback)
 {
     $this->objects = new ArrayObject();
     $this->callback = $callback;
     $this->dataObjectRecordProperty = new ReflectionProperty('DataObject', 'record');
     $this->dataObjectRecordProperty->setAccessible(true);
 }
Esempio n. 24
0
 public function testInitializeWithData()
 {
     $bag = new \Slim\Collection(array('foo' => 'bar'));
     $bagProperty = new \ReflectionProperty($bag, 'data');
     $bagProperty->setAccessible(true);
     $this->assertEquals(array('foo' => 'bar'), $bagProperty->getValue($bag));
 }
Esempio n. 25
0
 /**
  * @group mapper
  * @covers \PHPExif\Mapper\Native::mapRawData
  */
 public function testMapRawDataMapsFieldsCorrectly()
 {
     $reflProp = new \ReflectionProperty(get_class($this->mapper), 'map');
     $reflProp->setAccessible(true);
     $map = $reflProp->getValue($this->mapper);
     // ignore custom formatted data stuff:
     unset($map[\PHPExif\Mapper\Native::DATETIMEORIGINAL]);
     unset($map[\PHPExif\Mapper\Native::EXPOSURETIME]);
     unset($map[\PHPExif\Mapper\Native::FOCALLENGTH]);
     unset($map[\PHPExif\Mapper\Native::XRESOLUTION]);
     unset($map[\PHPExif\Mapper\Native::YRESOLUTION]);
     unset($map[\PHPExif\Mapper\Native::GPSLATITUDE]);
     unset($map[\PHPExif\Mapper\Native::GPSLONGITUDE]);
     // create raw data
     $keys = array_keys($map);
     $values = array();
     $values = array_pad($values, count($keys), 'foo');
     $rawData = array_combine($keys, $values);
     $mapped = $this->mapper->mapRawData($rawData);
     $i = 0;
     foreach ($mapped as $key => $value) {
         $this->assertEquals($map[$keys[$i]], $key);
         $i++;
     }
 }
 /**
  * Method to test duplicate().
  *
  * @param string $label
  * @param string $icon
  * @param string $id
  * @param string $prefix
  * @param string $task
  *
  * @covers       \Windwalker\Bootstrap\Dropdown::duplicate
  * @dataProvider duplicateProvider
  */
 public function testDuplicate($label, $icon, $id, $prefix, $task)
 {
     // Clean dropDownList property
     $this->refDropDownList->setValue(array());
     Dropdown::duplicate($id, $prefix);
     $this->assertEquals(array('<li>' . '<a href = "javascript://" onclick="listItemTask(\'cb' . $id . '\', \'' . $task . '\')">' . ($icon ? '<span class="icon-' . $icon . '"></span> ' : '') . $label . '</a>' . '</li>'), $this->refDropDownList->getValue());
 }
Esempio n. 27
0
 /**
  * Get protected/private attribute of object
  *
  * @param object &$object       Object containing attribute
  * @param string $attributeName Attribute name to fetch
  * @return mixed
  */
 public function getAttribute(&$object, $attributeName)
 {
     $class = is_object($object) ? get_class($object) : $object;
     $reflection = new \ReflectionProperty($class, $attributeName);
     $reflection->setAccessible(true);
     return $reflection->getValue($object);
 }
 /**
  * @param string|object $classOrObject
  * @param string        $attributeName
  * @param mixed         $attributeValue
  */
 public function writeAttribute($classOrObject, $attributeName, $attributeValue)
 {
     $rp = new \ReflectionProperty($classOrObject, $attributeName);
     $rp->setAccessible(true);
     $rp->setValue($classOrObject, $attributeValue);
     $rp->setAccessible(false);
 }
Esempio n. 29
0
 public function testSchedule()
 {
     $testIntegrationType = 'testIntegrationType';
     $testConnectorType = 'testConnectorType';
     $testId = 22;
     $integration = new Integration();
     $integration->setType($testIntegrationType);
     $integration->setEnabled(true);
     $ref = new \ReflectionProperty(get_class($integration), 'id');
     $ref->setAccessible(true);
     $ref->setValue($integration, $testId);
     $this->typesRegistry->addChannelType($testIntegrationType, new TestIntegrationType());
     $this->typesRegistry->addConnectorType($testConnectorType, $testIntegrationType, new TestTwoWayConnector());
     $that = $this;
     $uow = $this->getMockBuilder('Doctrine\\ORM\\UnitOfWork')->disableOriginalConstructor()->getMock();
     $this->em->expects($this->once())->method('getUnitOfWork')->will($this->returnValue($uow));
     $metadataFactory = $this->getMockBuilder('Doctrine\\ORM\\Mapping\\ClassMetadataFactory')->disableOriginalConstructor()->getMock();
     $metadataFactory->expects($this->once())->method('getMetadataFor')->will($this->returnValue(new ClassMetadata('testEntity')));
     $this->em->expects($this->once())->method('getMetadataFactory')->will($this->returnValue($metadataFactory));
     $uow->expects($this->once())->method('persist')->with($this->isInstanceOf('JMS\\JobQueueBundle\\Entity\\Job'))->will($this->returnCallback(function (Job $job) use($that, $testId, $testConnectorType) {
         $expectedArgs = ['--integration=' . $testId, sprintf('--connector=testConnectorType', $testConnectorType), '--params=a:0:{}'];
         $that->assertEquals($expectedArgs, $job->getArgs());
     }));
     $uow->expects($this->once())->method('computeChangeSet');
     $this->scheduler->schedule($integration, $testConnectorType, [], false);
 }
Esempio n. 30
0
 /**
  * Makes a given model-property accessible.
  *
  * @param object $model
  * @param int    $value
  * @param string $property
  *
  * @return mixed
  */
 public function reflect($model, $value, $property = 'id')
 {
     $attribute = new \ReflectionProperty($model, $property);
     $attribute->setAccessible(true);
     $attribute->setValue($model, $value);
     return $model;
 }