Example #1
0
 /**
  * Exports the PHP code
  *
  * @return string
  */
 public function exportCode()
 {
     $code_lines = array();
     $code_lines[] = '<?php';
     // Export the namespace
     if ($this->_reflection_class->getNamespaceName()) {
         $code_lines[] = '';
         $code_lines[] = 'namespace ' . $this->_reflection_class->getNamespaceName() . ';';
         $code_lines[] = '';
     }
     // Export the class' signature
     $code_lines[] = sprintf('%s%s%s %s%s%s', $this->_reflection_class->isAbstract() ? 'abstract ' : '', $this->_reflection_class->isFinal() ? 'final ' : '', $this->_reflection_class->isInterface() ? 'interface' : ($this->_reflection_class->isTrait() ? 'trait' : 'class'), $this->getClassName(), $this->_getParentClassName() ? " extends {$this->_getParentClassName()}" : '', $this->_getInterfaceNames() ? " implements " . join(', ', $this->_getInterfaceNames()) : '');
     $code_lines[] = '{';
     $code_lines[] = '';
     // Export constants
     foreach ($this->_reflection_class->getConstants() as $name => $value) {
         $reflection_constant = new ReflectionConstant($name, $value);
         $code_lines[] = "\t" . $reflection_constant->exportCode();
         $code_lines[] = '';
     }
     // Export properties
     foreach ($this->_reflection_class->getProperties() as $property) {
         $reflection_property = new ReflectionProperty($property);
         $code_lines[] = "\t" . $reflection_property->exportCode();
         $code_lines[] = '';
     }
     // Export methods
     foreach ($this->_reflection_class->getMethods() as $method) {
         $reflection_method = new ReflectionMethod($method);
         $code_lines[] = "\t" . $reflection_method->exportCode();
         $code_lines[] = '';
     }
     $code_lines[] = '}';
     return join("\n", $code_lines);
 }
 /**
  * Constructor.
  *
  * @param \ReflectionClass $class ReflectionClass object.
  * @param array $options Configuration options.
  */
 public function __construct(\ReflectionClass $class, array $options = array())
 {
     parent::__construct($options);
     $this->class = $class;
     $this->constants = $this->class->getConstants();
     // sort by constant name
     ksort($this->constants);
 }
Example #3
0
 public function testAllClassConstantsAreValidTypes()
 {
     $reflection = new \ReflectionClass('\\Desk\\Client');
     foreach ($reflection->getConstants() as $constant => $constantValue) {
         $this->assertTrue(Client::isValidType($constantValue), "Desk\\Client::isValidType() returns FALSE for class " . "constant \"{$constant}\", all Desk\\Client class " . "constants should be valid client types");
     }
 }
Example #4
0
 protected function identifiers()
 {
     $refl = new \ReflectionClass($this);
     $constants = $refl->getConstants();
     asort($constants);
     return $constants;
 }
Example #5
0
 /**
  * @throws Exception\InvalidEnumerationValueException
  * @throws Exception\InvalidEnumerationDefinitionException
  * @internal param string $class
  */
 protected static function loadValues()
 {
     $class = get_called_class();
     if (isset(static::$enumConstants[$class])) {
         return;
     }
     $reflection = new \ReflectionClass($class);
     $constants = $reflection->getConstants();
     $defaultValue = NULL;
     if (isset($constants['__default'])) {
         $defaultValue = $constants['__default'];
         unset($constants['__default']);
     }
     if (empty($constants)) {
         throw new Exception\InvalidEnumerationValueException(sprintf('No enumeration constants defined for "%s"', $class), 1381512807);
     }
     foreach ($constants as $constant => $value) {
         if (!is_int($value) && !is_string($value)) {
             throw new Exception\InvalidEnumerationDefinitionException(sprintf('Constant value must be of type integer or string; constant=%s; type=%s', $constant, is_object($value) ? get_class($value) : gettype($value)), 1381512797);
         }
     }
     $constantValueCounts = array_count_values($constants);
     arsort($constantValueCounts, SORT_NUMERIC);
     $constantValueCount = current($constantValueCounts);
     $constant = key($constantValueCounts);
     if ($constantValueCount > 1) {
         throw new Exception\InvalidEnumerationDefinitionException(sprintf('Constant value is not unique; constant=%s; value=%s; enum=%s', $constant, $constantValueCount, $class), 1381512859);
     }
     if ($defaultValue !== NULL) {
         $constants['__default'] = $defaultValue;
     }
     static::$enumConstants[$class] = $constants;
 }
 /**
  * @return Tx_PtExtbase_Utility_ConstantToSpeakingNameMapper
  */
 public function __construct()
 {
     $className = $this->getClassName();
     $constantsReflection = new ReflectionClass($className);
     $this->originalSpeakingNameToConstantMapping = $constantsReflection->getConstants();
     $this->buildMaps();
 }
 /**
  * @param \PhpSigep\Model\PreListaDePostagem $plp
  * @param int $idPlpCorreios
  * @param string $logoFile
  * @throws InvalidArgument
  *      Se o arquivo $logoFile não existir.
  */
 public function __construct($plp, $idPlpCorreios, $logoFile, $chancelas = array())
 {
     if ($logoFile && !@getimagesize($logoFile)) {
         throw new InvalidArgument('O arquivo "' . $logoFile . '" não existe.');
     }
     $this->plp = $plp;
     $this->idPlpCorreios = $idPlpCorreios;
     $this->logoFile = $logoFile;
     $rClass = new \ReflectionClass(__CLASS__);
     $tiposChancela = $rClass->getConstants();
     foreach ($chancelas as $chancela) {
         switch ($chancela) {
             case CartaoDePostagem::TYPE_CHANCELA_CARTA:
             case CartaoDePostagem::TYPE_CHANCELA_CARTA_2016:
                 $this->layoutCarta = $chancela;
                 break;
             case CartaoDePostagem::TYPE_CHANCELA_SEDEX:
             case CartaoDePostagem::TYPE_CHANCELA_SEDEX_2016:
                 $this->layoutSedex = $chancela;
                 break;
             case CartaoDePostagem::TYPE_CHANCELA_PAC:
             case CartaoDePostagem::TYPE_CHANCELA_PAC_2016:
                 $this->layoutPac = $chancela;
                 break;
             default:
                 throw new \PhpSigep\Pdf\Exception\InvalidChancelaEntry('O tipo de chancela deve ser uma das constantes da classe');
         }
     }
     $this->init();
 }
 public function imprimeProdutos()
 {
     $reflection = new ReflectionClass(__CLASS__);
     for ($i = 1; $i <= count($reflection->getConstants()); $i++) {
         echo $reflection->getConstant("PRODUTO{$i}") . PHP_EOL;
     }
 }
Example #9
0
function niceVarDump($obj, $ident = 0)
{
    $data = '';
    $data .= str_repeat(' ', $ident);
    $original_ident = $ident;
    $toClose = false;
    switch (gettype($obj)) {
        case 'object':
            $vars = (array) $obj;
            $data .= gettype($obj) . ' (' . get_class($obj) . ') (' . count($vars) . ") {\n";
            $ident += 2;
            foreach ($vars as $key => $var) {
                $type = '';
                $k = bin2hex($key);
                if (strpos($k, '002a00') === 0) {
                    $k = str_replace('002a00', '', $k);
                    $type = ':protected';
                } elseif (strpos($k, bin2hex("" . get_class($obj) . "")) === 0) {
                    $k = str_replace(bin2hex("" . get_class($obj) . ""), '', $k);
                    $type = ':private';
                }
                $k = hex2bin($k);
                if (is_subclass_of($obj, 'ProtobufMessage') && $k == 'values') {
                    $r = new ReflectionClass($obj);
                    $constants = $r->getConstants();
                    $newVar = [];
                    foreach ($constants as $ckey => $cval) {
                        if (substr($ckey, 0, 3) != 'PB_') {
                            $newVar[$ckey] = $var[$cval];
                        }
                    }
                    $var = $newVar;
                }
                $data .= str_repeat(' ', $ident) . "[{$k}{$type}]=>\n" . niceVarDump($var, $ident) . "\n";
            }
            $toClose = true;
            break;
        case 'array':
            $data .= 'array (' . count($obj) . ") {\n";
            $ident += 2;
            foreach ($obj as $key => $val) {
                $data .= str_repeat(' ', $ident) . '[' . (is_int($key) ? $key : "\"{$key}\"") . "]=>\n" . niceVarDump($val, $ident) . "\n";
            }
            $toClose = true;
            break;
        case 'string':
            $data .= 'string "' . parseText($obj) . "\"\n";
            break;
        case 'NULL':
            $data .= gettype($obj);
            break;
        default:
            $data .= gettype($obj) . '(' . strval($obj) . ")\n";
            break;
    }
    if ($toClose) {
        $data .= str_repeat(' ', $original_ident) . "}\n";
    }
    return $data;
}
 public static function client_commands_array()
 {
     $options = array('Test Installation' => array(), 'Testing' => array(), 'Batch Testing' => array(), 'OpenBenchmarking.org' => array(), 'System' => array(), 'Information' => array(), 'Asset Creation' => array(), 'Result Management' => array(), 'Result Analytics' => array(), 'Other' => array());
     foreach (pts_file_io::glob(PTS_COMMAND_PATH . '*.php') as $option_php_file) {
         $option_php = basename($option_php_file, '.php');
         $name = str_replace('_', '-', $option_php);
         if (!in_array(pts_strings::first_in_string($name, '-'), array('dump', 'task'))) {
             include_once $option_php_file;
             $reflect = new ReflectionClass($option_php);
             $constants = $reflect->getConstants();
             $doc_description = isset($constants['doc_description']) ? constant($option_php . '::doc_description') : 'No summary is available.';
             $doc_section = isset($constants['doc_section']) ? constant($option_php . '::doc_section') : 'Other';
             $name = isset($constants['doc_use_alias']) ? constant($option_php . '::doc_use_alias') : $name;
             $skip = isset($constants['doc_skip']) ? constant($option_php . '::doc_skip') : false;
             $doc_args = array();
             if ($skip) {
                 continue;
             }
             if (method_exists($option_php, 'argument_checks')) {
                 $doc_args = call_user_func(array($option_php, 'argument_checks'));
             }
             if (!empty($doc_section) && !isset($options[$doc_section])) {
                 $options[$doc_section] = array();
             }
             array_push($options[$doc_section], array($name, $doc_args, $doc_description));
         }
     }
     return $options;
 }
Example #11
0
 /**
  * Set attributes for a Doctrine_Configurable instance
  *
  * @param   Doctrine_Configurable $object
  * @param   array $attributes
  * @return  void
  * @throws  Zend_Application_Resource_Exception
  */
 protected function _setAttributes(Doctrine_Configurable $object, array $attributes)
 {
     $reflect = new ReflectionClass('ZFDoctrine_Core');
     $doctrineConstants = $reflect->getConstants();
     $attributes = array_change_key_case($attributes, CASE_UPPER);
     foreach ($attributes as $key => $value) {
         if (!array_key_exists($key, $doctrineConstants)) {
             throw new Zend_Application_Resource_Exception("Invalid attribute {$key}.");
         }
         $attrIdx = $doctrineConstants[$key];
         $attrVal = $value;
         if (Doctrine_Core::ATTR_QUERY_CACHE == $attrIdx) {
             $attrVal = $this->_getCache($value);
         } elseif (Doctrine_Core::ATTR_RESULT_CACHE == $attrIdx) {
             $attrVal = $this->_getCache($value);
         } else {
             if (is_string($value)) {
                 $value = strtoupper($value);
                 if (array_key_exists($value, $doctrineConstants)) {
                     $attrVal = $doctrineConstants[$value];
                 }
             }
         }
         $object->setAttribute($attrIdx, $attrVal);
     }
 }
Example #12
0
 /**
  * @param $serviceName string name of service to create
  * @param Common\Consumer\Credentials $credentials
  * @param Common\Storage\TokenStorageInterface $storage
  * @param array|null $scopes If creating an oauth2 service, array of scopes
  * @return ServiceInterface
  * @throws Common\Exception\Exception
  */
 public function createService($serviceName, Common\Consumer\Credentials $credentials, Common\Storage\TokenStorageInterface $storage, $scopes = array())
 {
     if (!$this->httpClient) {
         // for backwards compatibility.
         $this->httpClient = new \OAuth\Common\Http\Client\StreamClient();
     }
     $serviceName = ucfirst($serviceName);
     $v2ClassName = "\\OAuth\\OAuth2\\Service\\{$serviceName}";
     $v1ClassName = "\\OAuth\\OAuth1\\Service\\{$serviceName}";
     // if an oauth2 version exists, prefer it
     if (class_exists($v2ClassName)) {
         // resolve scopes
         $resolvedScopes = array();
         $reflClass = new \ReflectionClass($v2ClassName);
         $constants = $reflClass->getConstants();
         foreach ($scopes as $scope) {
             $key = strtoupper('SCOPE_' . $scope);
             // try to find a class constant with this name
             if (array_key_exists($key, $constants)) {
                 $resolvedScopes[] = $constants[$key];
             } else {
                 $resolvedScopes[] = $scope;
             }
         }
         return new $v2ClassName($credentials, $this->httpClient, $storage, $resolvedScopes);
     }
     if (class_exists($v1ClassName)) {
         if (!empty($scopes)) {
             throw new Common\Exception\Exception('Scopes passed to ServiceFactory::createService but an OAuth1 service was requested.');
         }
         $signature = new OAuth1\Signature\Signature($credentials);
         return new $v1ClassName($credentials, $this->httpClient, $storage, $signature);
     }
     return null;
 }
Example #13
0
 /**
  * Constructor
  *
  * @param    string     $platform    Platform
  * @param    DBFarmRole $DBFarmRole  optional Farm Role object
  * @param    int        $index       optional Server index within the Farm Role scope
  * @param    string     $role_id     optional Identifier of the Role
  */
 public function __construct($platform, DBFarmRole $DBFarmRole = null, $index = null, $role_id = null)
 {
     $this->platform = $platform;
     $this->dbFarmRole = $DBFarmRole;
     $this->index = $index;
     $this->roleId = $role_id === null ? $this->dbFarmRole->RoleID : $role_id;
     if ($DBFarmRole) {
         $this->envId = $DBFarmRole->GetFarmObject()->EnvID;
     }
     //Refletcion
     $Reflect = new ReflectionClass(DBServer::$platformPropsClasses[$this->platform]);
     foreach ($Reflect->getConstants() as $k => $v) {
         $this->platformProps[] = $v;
     }
     if ($DBFarmRole) {
         if (PlatformFactory::isOpenstack($this->platform)) {
             $this->SetProperties(array(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $DBFarmRole->CloudLocation));
         } elseif (PlatformFactory::isCloudstack($this->platform)) {
             $this->SetProperties(array(CLOUDSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $DBFarmRole->CloudLocation));
         } else {
             switch ($this->platform) {
                 case SERVER_PLATFORMS::GCE:
                     $this->SetProperties(array(GCE_SERVER_PROPERTIES::CLOUD_LOCATION => $DBFarmRole->CloudLocation));
                     break;
                 case SERVER_PLATFORMS::EC2:
                     $this->SetProperties(array(EC2_SERVER_PROPERTIES::REGION => $DBFarmRole->CloudLocation));
                     break;
             }
         }
     }
     $this->SetProperties(array(SERVER_PROPERTIES::SZR_VESION => '0.20.0'));
 }
Example #14
0
 /**
  * Uses reflection to find the constants defined in the class and cache
  * them in a local property for performance, before returning them.
  *
  * @param callable|null $keysCallback
  * @param bool          $classPrefixed      True if you want the enum class prefix on each keys, false otherwise.
  * @param string        $namespaceSeparator Only relevant if $classPrefixed is set to true.
  *
  * @return array a hash with your constants and their value. Useful for
  *               building a choice widget
  */
 public static final function getConstants($keysCallback = null, $classPrefixed = false, $namespaceSeparator = null)
 {
     $namespaceSeparator = $namespaceSeparator ?: static::$defaultNamespaceSeparator;
     $enumTypes = static::getEnumTypes();
     $enums = [];
     if (!is_array($enumTypes)) {
         $enumTypes = [$enumTypes];
     }
     foreach ($enumTypes as $key => $enumType) {
         $cacheKey = is_int($key) ? $enumType : $key;
         if (!isset(self::$constCache[$cacheKey])) {
             $reflect = new \ReflectionClass($enumType);
             self::$constCache[$cacheKey] = $reflect->getConstants();
         }
         if (count($enumTypes) > 1) {
             foreach (self::$constCache[$cacheKey] as $subKey => $value) {
                 $subKey = $cacheKey . (is_int($key) ? '::' : '.') . $subKey;
                 $enums[$subKey] = $value;
             }
         } else {
             $enums = self::$constCache[$cacheKey];
         }
     }
     if (is_callable($keysCallback) || $classPrefixed) {
         return array_combine($classPrefixed ? static::getClassPrefixedKeys($keysCallback, $namespaceSeparator) : static::getKeys($keysCallback), $enums);
     }
     return $enums;
 }
Example #15
0
 /**
  * Convenicene method to get readable names of each feature.
  */
 public static function getFeatures()
 {
     $ref = new \ReflectionClass('X10Device');
     $constants = $ref->getConstants();
     $returns = array();
     foreach ($constants as $key => $val) {
         if (substr($key, 0, 2) == 'F_') {
             $r = $key;
             switch ($key) {
                 case 'F_ON':
                     $r = 'On';
                     break;
                 case 'F_OFF':
                     $r = 'Off';
                     break;
                 case 'F_DIM':
                     $r = 'Dim';
                     break;
                 case 'F_BRIGHT':
                     $r = 'Bright';
                     break;
             }
             $returns[$val] = $r;
         }
     }
     return $returns;
 }
Example #16
0
 protected function checkResource($entity, $className)
 {
     $reflect = new ReflectionClass($className);
     if (!in_array($entity, $reflect->getConstants())) {
         throw new TypeException(__CLASS__, __METHOD__);
     }
 }
Example #17
0
 /**
  * @param string $hint
  * @param \ReflectionClass $class
  * @return Type
  */
 public function fromTypeHint($hint, \ReflectionClass $class)
 {
     $resolver = new ClassResolver($class);
     if (strtolower(substr($hint, -3)) == '-id') {
         $target = $resolver->resolve(substr($hint, 0, -3));
         return new IdentifierType($target, new StringType());
     } else {
         if (strpos($hint, '::') && substr($hint, -1) == '*') {
             list($container, $constant) = explode('::', substr($hint, 0, -1));
             if ($container == 'self') {
                 $reflection = $class;
             } else {
                 $reflection = new \ReflectionClass($resolver->resolve($container));
             }
             $options = [];
             foreach ($reflection->getConstants() as $name => $value) {
                 if (substr($name, 0, strlen($constant)) == $constant) {
                     $options[$value] = ucfirst($value);
                 }
             }
             return new EnumerationType($options, new StringType());
         } else {
             if (preg_match('#\\[\\d+;\\d+(;\\d+)?\\]#', $hint)) {
                 $parts = explode(';', substr($hint, 1, -1));
                 $min = array_shift($parts);
                 $max = array_shift($parts);
                 $step = $parts ? array_shift($parts) : 1;
                 return new RangeType($min, $max, $step);
             }
         }
     }
     return parent::fromTypeHint($hint, $class);
 }
Example #18
0
 /**
  * @param string $hint
  * @param \ReflectionClass $class
  * @return Type
  */
 public function fromTypeHint($hint, \ReflectionClass $class)
 {
     $resolver = new ClassResolver($class);
     if (strtolower(substr($hint, -3)) == '-id') {
         $target = $resolver->resolve(substr($hint, 0, -3));
         return new IdentifierType($target, new StringType());
     } else {
         if (strpos($hint, '::') && substr($hint, -1) == '*') {
             list($container, $constant) = explode('::', substr($hint, 0, -1));
             if ($container == 'self') {
                 $reflection = $class;
             } else {
                 $reflection = new \ReflectionClass($resolver->resolve($container));
             }
             $options = [];
             foreach ($reflection->getConstants() as $name => $value) {
                 if (substr($name, 0, strlen($constant)) == $constant) {
                     $options[$value] = ucfirst($value);
                 }
             }
             return new EnumerationType($options, new StringType());
         }
     }
     return parent::fromTypeHint($hint, $class);
 }
 /**
  * @return array of all policies data
  */
 public static function getAllModulePoliciesDataByPermitable(Permitable $permitable)
 {
     $data = array();
     $modules = Module::getModuleObjects();
     foreach ($modules as $module) {
         if ($module instanceof SecurableModule) {
             $moduleClassName = get_class($module);
             $policies = $moduleClassName::getPolicyNames();
             $policyLabels = $moduleClassName::getTranslatedPolicyLabels();
             $reflectionClass = new ReflectionClass($moduleClassName);
             $constants = $reflectionClass->getConstants();
             if (!empty($policies)) {
                 foreach ($policies as $policy) {
                     if (!isset($policyLabels[$policy])) {
                         throw new NotSupportedException();
                     }
                     $explicit = $permitable->getExplicitActualPolicy($moduleClassName, $policy);
                     $inherited = $permitable->getInheritedActualPolicy($moduleClassName, $policy);
                     $effective = $permitable->getEffectivePolicy($moduleClassName, $policy);
                     $constantId = array_search($policy, $constants);
                     $data[$moduleClassName][$constantId] = array('displayName' => $policyLabels[$policy], 'explicit' => $explicit, 'inherited' => $inherited, 'effective' => $effective);
                 }
             }
         }
     }
     return $data;
 }
Example #20
0
 /**
  * Runs the test.
  */
 public function test()
 {
     $content = file_get_contents(DIR_FILES . '/mail/logo.gif');
     $name = 'logo.gif';
     $cid = 'logo.gif';
     $mimeType = 'image/gif';
     $attachment = new InlineString($content, $name, $cid, $mimeType);
     $this->assertEquals($content, $attachment->getContent());
     $this->assertEquals($name, $attachment->getName());
     $this->assertEquals($mimeType, $attachment->getMimeType());
     $this->assertEquals(\Jyxo\Mail\Email\Attachment::DISPOSITION_INLINE, $attachment->getDisposition());
     $this->assertTrue($attachment->isInline());
     $this->assertEquals($cid, $attachment->getCid());
     $this->assertEquals('', $attachment->getEncoding());
     // It is possible to set an encoding
     $reflection = new \ReflectionClass('\\Jyxo\\Mail\\Encoding');
     foreach ($reflection->getConstants() as $encoding) {
         $attachment->setEncoding($encoding);
         $this->assertEquals($encoding, $attachment->getEncoding());
     }
     // Incompatible encoding
     try {
         $attachment->setEncoding('dummy-encoding');
         $this->fail('Expected exception \\InvalidArgumentException.');
     } catch (\PHPUnit_Framework_AssertionFailedError $e) {
         throw $e;
     } catch (\Exception $e) {
         // Correctly thrown exception
         $this->assertInstanceOf('\\InvalidArgumentException', $e);
     }
 }
Example #21
0
 /**
  * @return array of all module rights data
  */
 public static function getAllModuleRightsDataByPermitable(Permitable $permitable)
 {
     $data = array();
     $modules = Module::getModuleObjects();
     foreach ($modules as $module) {
         if ($module instanceof SecurableModule) {
             $moduleClassName = get_class($module);
             $rights = $moduleClassName::getRightsNames();
             $rightLabels = $moduleClassName::getTranslatedRightsLabels();
             $reflectionClass = new ReflectionClass($moduleClassName);
             if (!empty($rights)) {
                 $rightsData = array();
                 foreach ($rights as $right) {
                     if (!isset($rightLabels[$right])) {
                         throw new NotSupportedException($right);
                     }
                     $explicit = $permitable->getExplicitActualRight($moduleClassName, $right);
                     $inherited = $permitable->getInheritedActualRight($moduleClassName, $right);
                     $effective = $permitable->getEffectiveRight($moduleClassName, $right);
                     $constants = $reflectionClass->getConstants();
                     $constantId = array_search($right, $constants);
                     $rightsData[$constantId] = array('displayName' => $rightLabels[$right], 'explicit' => RightsUtil::getRightStringFromRight($explicit), 'inherited' => RightsUtil::getRightStringFromRight($inherited), 'effective' => RightsUtil::getRightStringFromRight($effective));
                 }
                 $data[$moduleClassName] = ArrayUtil::subValueSort($rightsData, 'displayName', 'asort');
             }
         }
     }
     return $data;
 }
Example #22
0
 public static function lists()
 {
     $rf = new \ReflectionClass("Canducci\\ZipCode\\ZipCodeUf");
     $data = $rf->getConstants();
     unset($rf);
     return $data;
 }
Example #23
0
 /**
  * Returns the elements of this enum class or null if this
  * Class object does not represent an enum type.
  *
  * @return an array containing the values comprising the enum class
  *     represented by this Class object in the order they're
  *     declared, or null if this Class object does not
  *     represent an enum type
  * @since 1.5
  */
 public function getEnumConstants()
 {
     if (!$this->isEnum()) {
         return null;
     }
     return $this->reflectionClass->getConstants();
 }
Example #24
0
 public static function load($path = '')
 {
     if (!empty($path) and !in_array($path, self::$loaded)) {
         $path = !empty($path) ? '\\' . trim($path, '\\') : '';
         $lang_class = '\\GCore' . $path . '\\Locales\\EnGb\\Lang';
         $cutsom_lang = '\\GCore' . $path . '\\Locales\\' . Str::camilize(str_replace('-', '_', strtolower(Base::getConfig('site_language', 'en-gb')))) . '\\Lang';
         if (class_exists($cutsom_lang)) {
             if (class_exists($lang_class)) {
                 //load default language as well
                 $lang_class_loaded = new \ReflectionClass($lang_class);
                 self::$translations = array_merge((array) self::$translations, $lang_class_loaded->getConstants(), $lang_class_loaded->getStaticProperties());
                 self::$loaded[] = $path;
             }
             $lang_class = $cutsom_lang;
         }
         if (!class_exists($lang_class)) {
             return false;
         }
         $lang_class_loaded = new \ReflectionClass($lang_class);
         self::$translations = array_merge((array) self::$translations, $lang_class_loaded->getConstants(), $lang_class_loaded->getStaticProperties());
         self::$loaded[] = $path;
         return true;
     }
     return false;
 }
Example #25
0
 public static function fromReflection(\ReflectionClass $ref)
 {
     $class = new static();
     $class->setName($ref->name)->setAbstract($ref->isAbstract())->setFinal($ref->isFinal())->setConstants($ref->getConstants());
     if (null === self::$phpParser) {
         if (!class_exists('Doctrine\\Common\\Annotations\\PhpParser')) {
             self::$phpParser = false;
         } else {
             self::$phpParser = new PhpParser();
         }
     }
     if (false !== self::$phpParser) {
         $class->setUseStatements(self::$phpParser->parseClass($ref));
     }
     if ($docComment = $ref->getDocComment()) {
         $class->setDocblock(ReflectionUtils::getUnindentedDocComment($docComment));
     }
     foreach ($ref->getMethods() as $method) {
         $class->setMethod(static::createMethod($method));
     }
     foreach ($ref->getProperties() as $property) {
         $class->setProperty(static::createProperty($property));
     }
     return $class;
 }
Example #26
0
 public static function logger($msg, $context = array(), $level = self::INFO)
 {
     if (class_exists('\\Monolog\\Logger', true)) {
         if (is_null(self::$logger)) {
             self::$logger = new \Monolog\Logger('pw\\Math');
             self::$logger->pushHandler(new \Monolog\Handler\ErrorLogHandler());
             self::$logger->pushProcessor(new \Monolog\Processor\PsrLogMessageProcessor());
         }
         self::$logger->addRecord($level, $msg, $context);
     } else {
         if (is_null(self::$logger)) {
             self::$logger = STDERR;
             $class = new \ReflectionClass(__CLASS__);
             foreach ($class->getConstants() as $key => $val) {
                 self::$levels[$val] = $key;
             }
         }
         $matches = array();
         $replace = array();
         foreach ($context as $key => $val) {
             $matches[] = '{' . $key . '}';
             $replace[] = $val;
         }
         $msg = explode("\n", str_replace($matches, $replace, $msg));
         $prefix = date("[Y-m-d H:i:s]");
         $prefix .= " pw\\Math." . self::$levels . "[{$level}] ";
         $msgs = "";
         foreach ($msg as $m) {
             $msgs .= $prefix . $m . PHP_EOL;
         }
         fwrite($self::$logger, $msgs);
     }
 }
Example #27
0
 public static function getLabel($code)
 {
     $class = new \ReflectionClass(get_class());
     $constants = $class->getConstants();
     $constants = array_flip($constants);
     return $constants[$code];
 }
Example #28
0
File: Enum.php Project: M1n0R/enum
 public static function all()
 {
     $reflection = new \ReflectionClass(static::class);
     $constants = $reflection->getConstants();
     unset($constants['__default']);
     return $constants;
 }
Example #29
0
 public static function getScriptingBuiltinVariables()
 {
     if (!self::$BUILTIN_VARIABLES_LOADED) {
         $ReflectEVENT_TYPE = new ReflectionClass("EVENT_TYPE");
         $event_types = $ReflectEVENT_TYPE->getConstants();
         foreach ($event_types as $event_type) {
             if (class_exists("{$event_type}Event")) {
                 $ReflectClass = new ReflectionClass("{$event_type}Event");
                 $retval = $ReflectClass->getMethod("GetScriptingVars")->invoke(null);
                 if (!empty($retval)) {
                     foreach ($retval as $k => $v) {
                         if (!self::$BUILTIN_VARIABLES[$k]) {
                             self::$BUILTIN_VARIABLES[$k] = array("PropName" => $v, "EventName" => "{$event_type}");
                         } else {
                             if (!is_array(self::$BUILTIN_VARIABLES[$k]['EventName'])) {
                                 $events = array(self::$BUILTIN_VARIABLES[$k]['EventName']);
                             } else {
                                 $events = self::$BUILTIN_VARIABLES[$k]['EventName'];
                             }
                             $events[] = $event_type;
                             self::$BUILTIN_VARIABLES[$k] = array("PropName" => $v, "EventName" => $events);
                         }
                     }
                 }
             }
         }
         foreach (self::$BUILTIN_VARIABLES as $k => $v) {
             self::$BUILTIN_VARIABLES["event_{$k}"] = $v;
         }
         self::$BUILTIN_VARIABLES_LOADED = true;
     }
     return self::$BUILTIN_VARIABLES;
 }
Example #30
0
 /**
  * Verifica que el tipo de mensaje enviado sea valido.
  * @param string $type Tipo de mensaje.
  * @throws \UnexpectedValueException Si no es un tipo de mensaje valido.
  */
 private static function validate($type)
 {
     $class = new \ReflectionClass(get_class());
     if (!in_array($type, $class->getConstants())) {
         throw new \UnexpectedValueException('Error building the message [type rejected].');
     }
 }