/** * Checks entity for this filter. * * @param mixed $entity * * @return bool */ public function __invoke($entity) { if (!is_object($entity) || !$this->class->isInstance($entity)) { return false; } $accepted = true; foreach (array_keys($this->criteria) as $criteria) { $accepted = $accepted && $this->{'check' . ucfirst($criteria) . 'Criteria'}($entity); // Optimization. if (!$accepted) { return $accepted; } } return $accepted; }
/** * @Then /^I should get an instance of "([^"]*)"$/ */ public function iShouldGetAnInstanceOf($instance) { $rc = new \ReflectionClass($instance); if (!$rc->isInstance(false === strpos($instance, 'Factory') ? $this->feed : $this->factory)) { throw new \Exception('This is not the feed factory'); } }
/** * Casts an object to the class or interface represented * by this <tt>Class</tt> object. * * @param obj the object to be cast * @return blaze\lang\Object the object after casting, or null if obj is null * * @throws ClassCastException if the object is not * null and is not assignable to the type T. * * @since 1.5 */ public function cast(Reflectable $obj) { if (!$this->reflectionClass->isInstance($obj)) { throw new ClassCastException(); } return $obj; }
/** */ public function testIsInstance() { $this->object->setName('\\Documentor\\Reflection\\ReflectionClass'); $this->assertFalse($this->object->isInstance(new \stdClass())); $this->assertTrue($this->object->isInstance(new ReflectionClass())); $this->setExpectedException('\\InvalidArgumentException'); $this->object->isInstance("string"); }
public function testShoppingOrderRateRequestFactory() { $factory = $this->getApplicationContext()->getComponent('\\FS\\Components\\Shipping\\Factory\\ShoppingOrderRateRequestFactory'); $options = $this->getApplicationContext()->getComponent('\\FS\\Components\\Options'); $request = $factory->setPayload(array('order' => $this->order, 'options' => $options))->getRequest(); $reflected = new \ReflectionClass('\\FS\\Components\\Shipping\\Factory\\FormattedRequestInterface'); $this->assertTrue(true, $reflected->isInstance($request)); $this->assertSame(array('from' => array('country' => 'CA', 'state' => 'QC', 'city' => 'POINTE-CLAIRE', 'postal_code' => 'H9R5P9', 'address' => '148 Brunswick', 'name' => 'FlagShip WooCommerce Test App', 'attn' => 'FlagShip Tester', 'phone' => '+1 866 320 8383', 'ext' => ''), 'to' => array('name' => 'WooCompany', 'attn' => 'Jeroen Sormani', 'address' => 'WooAddress', 'city' => 'WooCity', 'state' => 'NY', 'country' => 'US', 'postal_code' => '123456', 'phone' => ''), 'packages' => array('items' => array(0 => array('width' => 1, 'height' => 1, 'length' => 1, 'weight' => 4, 'description' => 'Flagship shipping package')), 'units' => 'imperial', 'type' => 'package'), 'payment' => array('payer' => 'F'), 'options' => array('address_correction' => true)), $request->getRequest()); }
/** * @throws \InvalidArgumentException * @param ItemInterface $item * @return Feed */ public function add(ItemInterface $item) { $rc = new \ReflectionClass($this->config['class']); if (!($rc->isInstance($item) || $item instanceof GenericItem)) { throw new \InvalidArgumentException('The class given MUST be an instance of "' . $this->config['class'] . '".'); } $this->items[] = $item; $this->autoSlice(); return $this; }
/** * Dynamically generates the object from the declared properties of the given object or array * * @param array|object $object * * @return \stdClass */ public static function toObject($object) { // If we can't iterate over the thing, we bail if (!is_object($object) && !is_array($object) && !$object instanceof \Traversable) { return null; } if (is_array($object)) { // Convert to an object $_properties = new \stdClass(); foreach ($object as $_key => $_value) { $_properties->{$_key} = $_value; } } else { $_me = new \ReflectionObject($object); $_properties = $_me->getProperties(); } // We'll return this $_obj = new \stdClass(); if (!empty($_properties)) { if (is_object($object)) { $_myClass = get_class($object); } else { $_myClass = '_array_'; } foreach ($_properties as $_property) { // Only want properties of $object hierarchy... if (isset($_property->class)) { $_class = new \ReflectionClass($_property->class); if (!empty($_class) && !$_class->isInstance($object) && !$_class->isSubclassOf($_myClass)) { unset($_class); continue; } unset($_class); } try { $_realPropertyName = $_propertyName = ltrim($_property->name, '_ '); if (false !== strpos($_propertyName, '_')) { $_propertyName = Inflector::tag($_propertyName); } $_getter = 'get' . $_propertyName; if (method_exists($object, $_getter)) { $_propertyValue = $object->{$_getter}(); if (!is_scalar($_propertyValue)) { $_propertyValue = self::toObject($_propertyValue); } $_obj->{$_realPropertyName} = $_propertyValue; } } catch (\Exception $_ex) { // Just ignore, not a valid property if we can't read it with a getter } } } return $_obj; }
/** * Compares two entities. * * @throws \InvalidArgumentException If entities can not be compared. * * @param mixed $entity1 * @param mixed $entity2 * * @return int */ public function __invoke($entity1, $entity2) { if (!$this->class->isInstance($entity1) || !$this->class->isInstance($entity2)) { throw new \InvalidArgumentException(); } $result = 0; foreach ($this->order as $property => $order) { $property1 = $entity1->{'get' . ucfirst($property)}(); $property2 = $entity2->{'get' . ucfirst($property)}(); $result = $this->{'compare' . ucfirst($this->properties[$property]) . 's'}($property1, $property2); if (self::ORDER_DESC == $order) { $result = -$result; } // Unless first success comparision. if ($result) { break; } } return $result; }
/** * @param mixed $object * @param string|\ReflectionClass $class * * @return bool */ public static function isInstanceOf($object, $class) { // TODO Validate $class. if (!is_object($class)) { $class = new \ReflectionClass($class); } if (is_object($object)) { return $class->isInstance($object); } else { return false; } }
public final function setApplicationContext(\FS\Context\ApplicationContextInterface $ctx = null) { if (!$this->ctx && !$this->isContextRequired()) { return $this; } $reflected = new \ReflectionClass($this->requiredContextClass()); if (!$this->ctx && !$reflected->isInstance($ctx)) { throw new \Exception('Invalid application context: needs to be of type [' . $this->requiredContextClass() . ']'); } $this->ctx = $ctx; return $this; }
public static function get() { $args = func_get_args(); $type = array_shift($args); $classname = ucwords($type) . __CLASS__; Log::debug(__CLASS__ . ': Getting new ' . $classname); $reflector = new ReflectionClass($classname); $dbdoclist = $reflector->newInstanceArgs($args); if ($reflector->isInstance($dbdoclist)) { return $dbdoclist; } else { Log::warning(__CLASS__ . ': Could not get new ' . $classname); return false; } }
public function readEntity(RoutingContextInterface $context, \ReflectionClass $ref, &$isRead) { if (!$ref->implementsInterface(EntityInterface::class)) { return; } $request = $context->getRequest(); if (!$request->hasEntity()) { return; } $entity = $request->getEntity(); if ($ref->isInstance($entity)) { $isRead = true; return $entity; } }
public static function get() { $args = func_get_args(); $doc_type = array_shift($args); $class_name = ucwords($doc_type) . 'DBDoc'; Log::debug(__CLASS__ . ': Getting instance of ' . $class_name); $reflector = new ReflectionClass($class_name); $dbdoc = $reflector->newInstanceArgs($args); Log::debug(__CLASS__ . ': Got new instance: ' . print_r($dbdoc, true)); if ($reflector->isInstance($dbdoc)) { return $dbdoc; } else { Log::debug(__CLASS__ . ': Could not get ' . $class_name); return false; } }
/** * Show reflection * * Show reflection * * <code> * Panda_Debug::reflect('BEAR_Form'); // Class * Panda_Debug::reflect($obj); // Objecy * Panda_Debug::reflect('p'); // Function * </code> * * @param string $target target * @param boll $cehckParent check parent class * * @return void */ public static function reflect($target, $cehckParent = false) { if (is_object($target)) { $target = get_class($target); } switch (true) { case function_exists($target): $ref = new ReflectionFunction($target); $info['name'] = $ref->isInternal() ? 'The internal ' : 'The user-defined '; $info['name'] .= $targetName = $ref->getName(); $info['declare in'] = $ref->getFileName() . ' lines ' . $ref->getStartLine() . ' to ' . $ref->getEndline(); $info['Documentation'] = $ref->getDocComment(); $statics = $ref->getStaticVariables(); if ($statics) { $info['Static variables'] = $statics; } $type = 'function'; break; case class_exists($target, false): $ref = new ReflectionClass($target); $type = 'class'; $info['name'] = $ref->isInternal() ? 'The internal ' : 'The user-defined '; $info['name'] .= $ref->isAbstract() ? ' abstract ' : ''; $info['name'] .= $ref->isFinal() ? ' final ' : ''; $info['name'] .= $ref->isInterface() ? 'interface ' : 'class '; $info['name'] .= $targetName = $ref->getName(); $info['declare in'] = $ref->getFileName() . ' lines ' . $ref->getStartLine() . ' to ' . $ref->getEndline(); $info['modifiers'] = Reflection::getModifierNames($ref->getModifiers()); $info['Documentation'] = $ref->getDocComment(); $info['Implements'] = $ref->getInterfaces(); $info['Constants'] = $ref->getConstants(); foreach ($ref->getProperties() as $prop) { // ReflectionProperty クラスのインスタンスを生成する $propRef = new ReflectionProperty($targetName, $prop->name); if ($propRef->isPublic()) { $porps[] = $prop->name; } } // $info['Public Properties'] = $porps; foreach ($ref->getMethods() as $method) { $methodRef = new ReflectionMethod($targetName, $method->name); if ($methodRef->isPublic() || $method->isStatic()) { $final = $method->isFinal() ? 'final ' : ''; $pubic = $method->isPublic() ? 'public ' : ''; $static = $method->isStatic() ? ' static ' : ''; $methods[] = sprintf("%s%s%s %s", $final, $pubic, $static, $method->name); } } $info['Public Methods'] = $methods; if ($ref->isInstantiable() && is_object($target)) { $info['isInstance ?'] = $ref->isInstance($target) ? 'yes' : 'no'; } if ($parent) { $info['parent'] .= $ref->getParentClass(); } break; default: $type = 'Invalid Object/Class'; $targetName = $target; $info = null; break; } print_a($info, "show_objects:1;label: Reflection of {$type} '{$targetName}'"); }
<?php class A { } class B extends A { } interface I { } class C implements I { } class X { } $classes = array("A", "B", "C", "I", "X"); $instances = array("myA" => new A(), "myB" => new B(), "myC" => new C(), "myX" => new X()); foreach ($classes as $class) { $rc = new ReflectionClass($class); foreach ($instances as $name => $instance) { echo "is {$name} a {$class}? "; var_dump($rc->isInstance($instance)); } }
function isBound($w) { $c = new ReflectionClass($w); return is_object($w) && $c->isInstance($w); }
/** * @param mixed $item * * @throws \InvalidArgumentException */ protected function checkType($item) { if (!is_object($item) || !$this->entityReflectionClass->isInstance($item)) { throw new \InvalidArgumentException(\sprintf('Expected %s instance, instance of %s given', $this->entityReflectionClass->name, \is_object($item) ? \gettype($item) : \get_class($item))); } }
public function isInstance($instance) { return $this->reflectionClass->isInstance($instance); }
/** * Returns all members for the called enum class * * @return lang.Enum[] */ public static function values() { $r = []; $c = new \ReflectionClass(get_called_class()); foreach ($c->getStaticProperties() as $prop) { if ($prop instanceof self && $c->isInstance($prop)) { $r[] = $prop; } } return $r; }
/** * Is correct item * * @param \ReflectionClass $reflector * * @return bool */ protected function isCorrectItem(\ReflectionClass $reflector) { if ($reflector->isInstance($this)) { return false; } if (!$this->hasClassInterface($reflector, 'Apishka\\EasyExtend\\RouterInterface')) { return false; } return true; }
} class C extends A { } $ra = new ReflectionClass('A'); $rc = new ReflectionClass('C'); $rd = new ReflectionClass('D'); $re = new ReflectionClass('E'); $ca = $ra->newInstance(); $cc = $rc->newInstance(); $cd = $rd->newInstance(); $ce = $re->newInstance(); print "Is? A " . ($ra->isInstance($ca) ? 'true' : 'false') . ", instanceof: " . ($ca instanceof A ? 'true' : 'false') . "\n"; print "Is? C " . ($rc->isInstance($ca) ? 'true' : 'false') . ", instanceof: " . ($ca instanceof C ? 'true' : 'false') . "\n"; print "Is? D " . ($rd->isInstance($ca) ? 'true' : 'false') . ", instanceof: " . ($ca instanceof D ? 'true' : 'false') . "\n"; print "Is? E " . ($re->isInstance($ca) ? 'true' : 'false') . ", instanceof: " . ($ca instanceof E ? 'true' : 'false') . "\n"; print "-\n"; print "Is? A " . ($ra->isInstance($cc) ? 'true' : 'false') . ", instanceof: " . ($cc instanceof A ? 'true' : 'false') . "\n"; print "Is? C " . ($rc->isInstance($cc) ? 'true' : 'false') . ", instanceof: " . ($cc instanceof C ? 'true' : 'false') . "\n"; print "Is? D " . ($rd->isInstance($cc) ? 'true' : 'false') . ", instanceof: " . ($cc instanceof D ? 'true' : 'false') . "\n"; print "Is? E " . ($re->isInstance($cc) ? 'true' : 'false') . ", instanceof: " . ($cc instanceof E ? 'true' : 'false') . "\n"; print "-\n"; print "Is? A " . ($ra->isInstance($cd) ? 'true' : 'false') . ", instanceof: " . ($cd instanceof A ? 'true' : 'false') . "\n"; print "Is? C " . ($rc->isInstance($cd) ? 'true' : 'false') . ", instanceof: " . ($cd instanceof C ? 'true' : 'false') . "\n"; print "Is? D " . ($rd->isInstance($cd) ? 'true' : 'false') . ", instanceof: " . ($cd instanceof D ? 'true' : 'false') . "\n"; print "Is? E " . ($re->isInstance($cd) ? 'true' : 'false') . ", instanceof: " . ($cd instanceof E ? 'true' : 'false') . "\n"; print "-\n"; print "Is? A " . ($ra->isInstance($ce) ? 'true' : 'false') . ", instanceof: " . ($ce instanceof A ? 'true' : 'false') . "\n"; print "Is? C " . ($rc->isInstance($ce) ? 'true' : 'false') . ", instanceof: " . ($ce instanceof C ? 'true' : 'false') . "\n"; print "Is? D " . ($rd->isInstance($ce) ? 'true' : 'false') . ", instanceof: " . ($ce instanceof D ? 'true' : 'false') . "\n"; print "Is? E " . ($re->isInstance($ce) ? 'true' : 'false') . ", instanceof: " . ($ce instanceof E ? 'true' : 'false') . "\n";
/** * checks if given type and type of value are a mismatch * * A type mismatch is defined as follows: $value is an object and it's * an instance of the class defined with $type. In any other case there's no * type mismatch * * @param string|\ReflectionClass $type * @param mixed $value * @return bool */ private function isTypeMismatch($type, $value) : bool { if (!$type instanceof \ReflectionClass) { return false; } if (!is_object($value)) { return true; } return !$type->isInstance($value); }
public function canProject($input) { return is_object($input) && $this->ref->isInstance($input); }
print "--- hasProperty() ---\n"; var_dump($rb->hasProperty('p0')); var_dump($rb->hasProperty('p4')); print "\n"; print "--- implementsInterface() ---\n"; var_dump($rb->implementsInterface('H')); var_dump($rb->implementsInterface('L')); print "\n"; print "--- isAbstract() ---\n"; var_dump($rb->isAbstract()); print "\n"; print "--- isFinal() ---\n"; var_dump($rb->isFinal()); print "\n"; print "--- isInstance() ---\n"; var_dump($rb->isInstance(new B())); var_dump($rb->isInstance(new C())); print "\n"; print "--- isInstantiable() ---\n"; var_dump($rb->isInstantiable()); print "\n"; print "--- isInterface() ---\n"; var_dump($rb->isInterface()); print "\n"; print "--- isInternal() ---\n"; var_dump($rb->isInternal()); print "\n"; print "--- isIterateable() ---\n"; var_dump($rb->isIterateable()); print "\n"; print "--- isSubclassOf() ---\n";
/** * Will figure out if a reference is still scheduled inside the UoW or just mapped * as an referenced object. * * @param $referencedObject * @return bool */ public function isReferenced($referencedObject) { $allScheduledReferences = $this->unitOfWork->getAllScheduledReferences(); $reflection = new \ReflectionClass($referencedObject); foreach ($allScheduledReferences as $references) { foreach ($references as $reference) { if ($reflection->isInstance($reference)) { return true; } } } return $this->unitOfWork->hasReferencedObject($referencedObject); }
class Counter extends Object implements MyInterface { const START = 0; private static $c = Counter::START; public function count() { return self::$c++; } } // Создание экземпляра класса ReflectionClass $class = new ReflectionClass('Counter'); // Вывод основной информации printf("===> %s%s%s %s '%s' [экземпляр класса %s]\n" . " объявлен в %s\n" . " строки с %d по %d\n", $class->isInternal() ? 'Встроенный' : 'Пользовательский', $class->isAbstract() ? ' абстрактный' : '', $class->isFinal() ? ' финальный' : '', $class->isInterface() ? 'интерфейс' : 'класс', $class->getName(), var_export($class->getParentClass(), 1), $class->getFileName(), $class->getStartLine(), $class->getEndline()); // Вывод тех интерфейсов, которые реализует этот класс printf("---> Интерфейсы:\n %s\n", var_export($class->getInterfaces(), 1)); // Вывод констант класса printf("---> Константы: %s\n", var_export($class->getConstants(), 1)); // Вывод свойств класса printf("---> Свойства: %s\n", var_export($class->getProperties(), 1)); // Вывод методов класса printf("---> Методы: %s\n", var_export($class->getMethods(), 1)); // Если есть возможность создать экземпляр класса, то создаем его if ($class->isInstantiable()) { $counter = $class->newInstance(); echo '---> Создан ли экземпляр класса ' . $class->getName() . '? '; echo $class->isInstance($counter) ? 'Да' : 'Нет'; echo "\n---> Создан ли экземпляр класса Object()? "; echo $class->isInstance(new Object()) ? 'Да' : 'Нет'; } ?> </pre>
* * @access public * @return int */ public function count() { return self::$c++; } } $class = new ReflectionClass('Counter'); printf("===> The %s%s%s %s '%s' [extends %s]" . " declared in %s" . " lines %d to %d" . " having the modifiers %d [%s]<br/>", $class->isInternal() ? 'internal' : 'user-defined', $class->isAbstract() ? ' abstract' : '', $class->isFinal() ? ' final' : '', $class->isInterface() ? 'interface' : 'class', $class->getName(), var_export($class->getParentClass(), 1), $class->getFileName(), $class->getStartLine(), $class->getEndline(), $class->getModifiers(), implode(' ', Reflection::getModifierNames($class->getModifiers()))); // output: ===> The user-defined class 'Counter' [extends ReflectionClass::__set_state(array( 'name' => 'Object', ))] declared in /home/cg/root/main.php lines 15 to 31 having the modifiers 524288 [] printf("===> Documentation:%s<br/>", var_export($class->getDocComment(), 1)); // output: ===> Documentation:'/** * A counter class */' printf("===> Implements:%s<br/>", var_export($class->getInterfaces(), 1)); // output: ===> Implements:array ( 'NSerializable' => ReflectionClass::__set_state(array( 'name' => 'NSerializable', )), ) printf("===> Constants: %s<br/>", var_export($class->getConstants(), 1)); // output: ===> Constants: array ( 'START' => 0, ) printf("===> Properties: %s<br/>", var_export($class->getProperties(), 1)); // output: ===> Properties: array ( 0 => ReflectionProperty::__set_state(array( 'name' => 'c', 'class' => 'Counter', )), ) printf("===> Methods: %s<br/>", var_export($class->getMethods(), 1)); // output: ===> Methods: array ( 0 => ReflectionMethod::__set_state(array( 'name' => 'count', 'class' => 'Counter', )), ) if ($class->isInstantiable()) { $counter = $class->newInstance(); echo '===> $counter is instance? '; echo $class->isInstance($counter) ? 'yes' : 'no'; //output: ===> $counter is instance? yes echo "<br/>===> new Object() is instance? "; echo $class->isInstance(new Object()) ? 'yes' : 'no'; //output: ===> new Object() is instance? no }
/** * @{inheritDoc} */ public function supports(StatefulInterface $object) { $reflection = new \ReflectionClass($this->config['class']); return $reflection->isInstance($object); }
/** * @{inheritDoc} */ public function supports($object, $graph = 'default') { $reflection = new \ReflectionClass($this->config['class']); return $reflection->isInstance($object) && $graph === $this->config['graph']; }
/** * @dataProvider dataObjectClasses */ public function testNewInstance($class) { $metadata = $this->getMetadataFor($class); $reflection = new \ReflectionClass('Tests\\NForms\\Models\\' . $class); Assert::true($reflection->isInstance($metadata->newInstance())); }