Example #1
1
 function convert_uudecode($string)
 {
     // Sanity check
     if (!is_scalar($string)) {
         user_error('convert_uuencode() expects parameter 1 to be string, ' . gettype($string) . ' given', E_USER_WARNING);
         return false;
     }
     if (strlen($string) < 8) {
         user_error('convert_uuencode() The given parameter is not a valid uuencoded string', E_USER_WARNING);
         return false;
     }
     $decoded = '';
     foreach (explode("\n", $string) as $line) {
         $c = count($bytes = unpack('c*', substr(trim($line), 1)));
         while ($c % 4) {
             $bytes[++$c] = 0;
         }
         foreach (array_chunk($bytes, 4) as $b) {
             $b0 = $b[0] == 0x60 ? 0 : $b[0] - 0x20;
             $b1 = $b[1] == 0x60 ? 0 : $b[1] - 0x20;
             $b2 = $b[2] == 0x60 ? 0 : $b[2] - 0x20;
             $b3 = $b[3] == 0x60 ? 0 : $b[3] - 0x20;
             $b0 <<= 2;
             $b0 |= $b1 >> 4 & 0x3;
             $b1 <<= 4;
             $b1 |= $b2 >> 2 & 0xf;
             $b2 <<= 6;
             $b2 |= $b3 & 0x3f;
             $decoded .= pack('c*', $b0, $b1, $b2);
         }
     }
     return rtrim($decoded, "");
 }
Example #2
1
 public function testSettersGetters()
 {
     $client = new Google_Client();
     $client->setClientId("client1");
     $client->setClientSecret('client1secret');
     $client->setState('1');
     $client->setApprovalPrompt('force');
     $client->setAccessType('offline');
     $client->setRedirectUri('localhost');
     $client->setApplicationName('me');
     $this->assertEquals('object', gettype($client->getAuth()));
     $this->assertEquals('object', gettype($client->getCache()));
     $this->assertEquals('object', gettype($client->getIo()));
     $client->setAuth(new Google_Auth_Simple($client));
     $client->setAuth(new Google_Auth_OAuth2($client));
     try {
         $client->setAccessToken(null);
         die('Should have thrown an Google_Auth_Exception.');
     } catch (Google_Auth_Exception $e) {
         $this->assertEquals('Could not json decode the token', $e->getMessage());
     }
     $token = json_encode(array('access_token' => 'token'));
     $client->setAccessToken($token);
     $this->assertEquals($token, $client->getAccessToken());
 }
Example #3
1
 /**
  * Sets selected items (by keys).
  * @param  array
  * @return self
  */
 public function setValue($values)
 {
     if (is_scalar($values) || $values === NULL) {
         $values = (array) $values;
     } elseif (!is_array($values)) {
         throw new Nette\InvalidArgumentException(sprintf("Value must be array or NULL, %s given in field '%s'.", gettype($values), $this->name));
     }
     $flip = [];
     foreach ($values as $value) {
         if (!is_scalar($value) && !method_exists($value, '__toString')) {
             throw new Nette\InvalidArgumentException(sprintf("Values must be scalar, %s given in field '%s'.", gettype($value), $this->name));
         }
         $flip[(string) $value] = TRUE;
     }
     $values = array_keys($flip);
     if ($this->checkAllowedValues && ($diff = array_diff($values, array_keys($this->items)))) {
         $set = Nette\Utils\Strings::truncate(implode(', ', array_map(function ($s) {
             return var_export($s, TRUE);
         }, array_keys($this->items))), 70, '...');
         $vals = (count($diff) > 1 ? 's' : '') . " '" . implode("', '", $diff) . "'";
         throw new Nette\InvalidArgumentException("Value{$vals} are out of allowed set [{$set}] in field '{$this->name}'.");
     }
     $this->value = $values;
     return $this;
 }
Example #4
0
 function bcinvert($a, $n)
 {
     // Sanity check
     if (!is_scalar($a)) {
         user_error('bcinvert() expects parameter 1 to be string, ' . gettype($a) . ' given', E_USER_WARNING);
         return false;
     }
     if (!is_scalar($n)) {
         user_error('bcinvert() expects parameter 2 to be string, ' . gettype($n) . ' given', E_USER_WARNING);
         return false;
     }
     $u1 = $v2 = '1';
     $u2 = $v1 = '0';
     $u3 = $n;
     $v3 = $a;
     while (bccomp($v3, '0')) {
         $q0 = bcdiv($u3, $v3);
         $t1 = bcsub($u1, bcmul($q0, $v1));
         $t2 = bcsub($u2, bcmul($q0, $v2));
         $t3 = bcsub($u3, bcmul($q0, $v3));
         $u1 = $v1;
         $u2 = $v2;
         $u3 = $v3;
         $v1 = $t1;
         $v2 = $t2;
         $v3 = $t3;
     }
     if (bccomp($u2, '0') < 0) {
         return bcadd($u2, $n);
     } else {
         return bcmod($u2, $n);
     }
 }
Example #5
0
 /**
  * Serialize the data for storing.
  *
  * Serializes the given $data to a executable PHP code representation 
  * string. This works with objects implementing {@link ezcBaseExportable},
  * arrays and scalar values (int, bool, float, string). The return value is
  * executable PHP code to be stored to disk. The data can be unserialized 
  * using the {@link fetchData()} method.
  * 
  * @param mixed $data
  * @return string
  *
  * @throws ezcCacheInvalidDataException
  *         if the $data can not be serialized (e.g. an object that does not
  *         implement ezcBaseExportable, a resource, ...).
  */
 protected function prepareData($data)
 {
     if (is_object($data) && !$data instanceof ezcBaseExportable || is_resource($data)) {
         throw new ezcCacheInvalidDataException(gettype($data), array('simple', 'array', 'ezcBaseExportable'));
     }
     return "<?php\nreturn " . var_export($data, true) . ";\n?>\n";
 }
Example #6
0
 /**
  * Constructor.
  *
  * @param string|number $value value to store in this numericNode
  * @throws \TYPO3\CMS\Fluid\Core\Parser\Exception
  */
 public function __construct($value)
 {
     if (!is_numeric($value)) {
         throw new \TYPO3\CMS\Fluid\Core\Parser\Exception('Numeric node requires an argument of type number, "' . gettype($value) . '" given.', 1360414192);
     }
     $this->value = $value + 0;
 }
Example #7
0
 function convert_uuencode($string)
 {
     // Sanity check
     if (!is_scalar($string)) {
         user_error('convert_uuencode() expects parameter 1 to be string, ' . gettype($string) . ' given', E_USER_WARNING);
         return false;
     }
     $u = 0;
     $encoded = '';
     while ($c = count($bytes = unpack('c*', substr($string, $u, 45)))) {
         $u += 45;
         $encoded .= pack('c', $c + 0x20);
         while ($c % 3) {
             $bytes[++$c] = 0;
         }
         foreach (array_chunk($bytes, 3) as $b) {
             $b0 = ($b[0] & 0xfc) >> 2;
             $b1 = (($b[0] & 0x3) << 4) + (($b[1] & 0xf0) >> 4);
             $b2 = (($b[1] & 0xf) << 2) + (($b[2] & 0xc0) >> 6);
             $b3 = $b[2] & 0x3f;
             $b0 = $b0 ? $b0 + 0x20 : 0x60;
             $b1 = $b1 ? $b1 + 0x20 : 0x60;
             $b2 = $b2 ? $b2 + 0x20 : 0x60;
             $b3 = $b3 ? $b3 + 0x20 : 0x60;
             $encoded .= pack('c*', $b0, $b1, $b2, $b3);
         }
         $encoded .= "\n";
     }
     // Add termination characters
     $encoded .= "`\n";
     return $encoded;
 }
 /**
  * Configures the view resolver.
  *
  * @param \Es\Modules\ModulesEvent $event The modules event
  *
  * @throws \UnexpectedValueException If configuration has invalid
  *                                   specification of view resolver
  */
 public function __invoke(ModulesEvent $event)
 {
     $modules = $this->getModules();
     $resolver = $this->getResolver();
     foreach ($modules as $name => $module) {
         $resolver->registerModulePath($name, $module->getModuleDir());
     }
     $config = $this->getConfig();
     if (!isset($config['view']['resolver'])) {
         return;
     }
     $map = (array) $config['view']['resolver'];
     foreach ($map as $key => $value) {
         if (is_array($value)) {
             foreach ($value as $template => $path) {
                 if (!is_string($path)) {
                     throw new UnexpectedValueException(sprintf('Invalid specification of view resolver for "%s" ' . 'provided; the path of template "%s" must be an ' . 'string, "%s" received.', $key, $template, is_object($path) ? get_class($path) : gettype($path)));
                 }
                 $template = Resolver::getFullTemplateName($key, $template);
                 $resolver->registerTemplatePath($template, $path);
             }
         } elseif (is_string($value)) {
             $resolver->registerTemplatePath($key, $value);
         } else {
             throw new UnexpectedValueException(sprintf('Invalid specification of view resolver provided; ' . '"%s" must be an string or an array, "%s" received.', $key, is_object($value) ? get_class($value) : gettype($value)));
         }
     }
 }
 protected function normalize($data)
 {
     if (null === $data || is_scalar($data)) {
         return $data;
     }
     if (is_array($data) || $data instanceof \Traversable) {
         $normalized = array();
         $count = 1;
         foreach ($data as $key => $value) {
             if ($count++ >= 1000) {
                 $normalized['...'] = 'Over 1000 items, aborting normalization';
                 break;
             }
             $normalized[$key] = $this->normalize($value);
         }
         return $normalized;
     }
     if ($data instanceof \DateTime) {
         return $data->format($this->dateFormat);
     }
     if (is_object($data)) {
         if ($data instanceof Exception) {
             return $this->normalizeException($data);
         }
         return sprintf("[object] (%s: %s)", get_class($data), $this->toJson($data, true));
     }
     if (is_resource($data)) {
         return '[resource]';
     }
     return '[unknown(' . gettype($data) . ')]';
 }
 public function __construct($var)
 {
     if (!is_object($var)) {
         throw new \RuntimeException('Argument 1 passed to ' . get_class($this) . ' must be an object, var of type ' . gettype($var) . ' given');
     }
     $this->storage = $var;
 }
Example #11
0
function json_nukeempty(&$data)
{
    if (gettype($data) == 'object') {
        $data = get_object_vars($data);
    }
    if (!is_array($data)) {
        return;
    }
    foreach ($data as $key => $dummy) {
        if (gettype($data[$key]) == 'string') {
            if ($dummy === "") {
                unset($data[$key]);
            }
            continue;
        }
        if (gettype($data[$key]) == 'object') {
            $data[$key] = get_object_vars($data[$key]);
        }
        if (!is_array($data[$key])) {
            continue;
        }
        if (count($data[$key]) > 0) {
            json_nukeempty($data[$key]);
        }
        if (count($data[$key]) == 0) {
            unset($data[$key]);
        }
    }
}
 /**
  * Check if $value is a Stylesheet object.
  * 
  * @throws InvalidArgumentException If $value is not a Stylesheet object.
  */
 protected function checkType($value)
 {
     if (!$value instanceof Stylesheet) {
         $msg = "StylesheetCollection class only accept Stylesheet objects, '" . gettype($value) . "' given.";
         throw new InvalidArgumentException($msg);
     }
 }
 /**
  * Attempt to get the method signatures in one request via system.multicall().
  * This is a boxcar feature of XML-RPC and is found on fewer servers.  However,
  * can significantly improve performance if present.
  *
  * @param  array $methods
  * @return array array(array(return, param, param, param...))
  */
 public function getSignatureForEachMethodByMulticall($methods = null)
 {
     if ($methods === null) {
         $methods = $this->listMethods();
     }
     $multicallParams = array();
     foreach ($methods as $method) {
         $multicallParams[] = array('methodName' => 'system.methodSignature', 'params' => array($method));
     }
     $serverSignatures = $this->_system->multicall($multicallParams);
     if (!is_array($serverSignatures)) {
         $type = gettype($serverSignatures);
         $error = "Multicall return is malformed.  Expected array, got {$type}";
         require_once 'Zend/XmlRpc/Client/IntrospectException.php';
         throw new Zend_XmlRpc_Client_IntrospectException($error);
     }
     if (count($serverSignatures) != count($methods)) {
         $error = 'Bad number of signatures received from multicall';
         require_once 'Zend/XmlRpc/Client/IntrospectException.php';
         throw new Zend_XmlRpc_Client_IntrospectException($error);
     }
     // Create a new signatures array with the methods name as keys and the signature as value
     $signatures = array();
     foreach ($serverSignatures as $i => $signature) {
         $signatures[$methods[$i]] = $signature;
     }
     return $signatures;
 }
/**
 * Memoizes callbacks and returns their value instead of calling them
 *
 * @param callable $callback Callable closure or function
 * @param array $arguments Arguments
 * @param array|string $key Optional memoize key to override the auto calculated hash
 * @return mixed
 */
function memoize($callback, array $arguments = array(), $key = null)
{
    static $storage = array();
    if ($callback === null) {
        $storage = array();
        return null;
    }
    InvalidArgumentException::assertCallback($callback, __FUNCTION__, 1);
    static $keyGenerator = null;
    if (!$keyGenerator) {
        $keyGenerator = function ($value) use(&$keyGenerator) {
            $type = gettype($value);
            if ($type === 'array') {
                $key = join(':', map($value, $keyGenerator));
            } elseif ($type === 'object') {
                $key = get_class($value) . ':' . spl_object_hash($value);
            } else {
                $key = (string) $value;
            }
            return $key;
        };
    }
    if ($key === null) {
        $key = $keyGenerator(array_merge(array($callback), $arguments));
    } else {
        $key = $keyGenerator($key);
    }
    if (!isset($storage[$key]) && !array_key_exists($key, $storage)) {
        $storage[$key] = call_user_func_array($callback, $arguments);
    }
    return $storage[$key];
}
 /**
  * Constructor
  *
  * Add a default initializer to ensure the plugin is valid after instance
  * creation.
  *
  * Additionally, the constructor provides forwards compatibility with v3 by
  * overloading the initial argument. v2 usage expects either null or a
  * ConfigInterface instance, and will ignore any other arguments. v3 expects
  * a ContainerInterface instance, and will use an array of configuration to
  * seed the current instance with services. In most cases, you can ignore the
  * constructor unless you are writing a specialized factory for your plugin
  * manager or overriding it.
  *
  * @param null|ConfigInterface|ContainerInterface $configOrContainerInstance
  * @param array $v3config If $configOrContainerInstance is a container, this
  *     value will be passed to the parent constructor.
  * @throws Exception\InvalidArgumentException if $configOrContainerInstance
  *     is neither null, nor a ConfigInterface, nor a ContainerInterface.
  */
 public function __construct($configOrContainerInstance = null, array $v3config = [])
 {
     if (null !== $configOrContainerInstance && !$configOrContainerInstance instanceof ConfigInterface && !$configOrContainerInstance instanceof ContainerInterface) {
         throw new Exception\InvalidArgumentException(sprintf('%s expects a ConfigInterface instance or ContainerInterface instance; received %s', get_class($this), is_object($configOrContainerInstance) ? get_class($configOrContainerInstance) : gettype($configOrContainerInstance)));
     }
     if ($configOrContainerInstance instanceof ContainerInterface) {
         if (property_exists($this, 'serviceLocator')) {
             if (!empty($v3config)) {
                 parent::__construct(new Config($v3config));
             }
             $this->serviceLocator = $configOrContainerInstance;
         }
         if (property_exists($this, 'creationContext')) {
             if (!empty($v3config)) {
                 parent::__construct($v3config);
             }
             $this->creationContext = $configOrContainerInstance;
         }
     }
     if ($configOrContainerInstance instanceof ConfigInterface) {
         parent::__construct($configOrContainerInstance);
     }
     $this->addInitializer(function ($instance) {
         if ($instance instanceof ServiceLocatorAwareInterface) {
             $instance->setServiceLocator($this);
         }
     });
 }
function arrayToJsArray($array, $name, $nl = "\n", $encoding = false)
{
    if (is_array($array)) {
        $jsArray = $name . ' = new Array();' . $nl;
        foreach ($array as $key => $value) {
            switch (gettype($value)) {
                case 'unknown type':
                case 'resource':
                case 'object':
                    break;
                case 'array':
                    $jsArray .= arrayToJsArray($value, $name . '[' . valueToJsValue($key, $encoding) . ']', $nl);
                    break;
                case 'NULL':
                    $jsArray .= $name . '[' . valueToJsValue($key, $encoding) . '] = null;' . $nl;
                    break;
                case 'boolean':
                    $jsArray .= $name . '[' . valueToJsValue($key, $encoding) . '] = ' . ($value ? 'true' : 'false') . ';' . $nl;
                    break;
                case 'string':
                    $jsArray .= $name . '[' . valueToJsValue($key, $encoding) . '] = ' . valueToJsValue($value, $encoding) . ';' . $nl;
                    break;
                case 'double':
                case 'integer':
                    $jsArray .= $name . '[' . valueToJsValue($key, $encoding) . '] = ' . $value . ';' . $nl;
                    break;
                default:
                    trigger_error('Hoppa, egy j t�us a PHP-ben?' . __CLASS__ . '::' . __FUNCTION__ . '()!', E_USER_WARNING);
            }
        }
        return $jsArray;
    } else {
        return false;
    }
}
Example #17
0
 /**
  * Encapsulate data within a directed graph vertex
  *
  * @param object $data
  */
 function __construct($data)
 {
     if (!is_object($data)) {
         throw new Exception('data must be an object, was ' . gettype($data));
     }
     $this->data = $data;
 }
Example #18
0
 function __construct($seed)
 {
     /* Handle simple type cases */
     if (!$seed instanceof akStoryEntry) {
         if ('string' == gettype($seed)) {
             $this->path = $seed;
         } else {
             /* Not a string, treat as integer */
             $this->id = $seed;
         }
     } else {
         /* Copy from an akStoryEntry (DB entry) */
         $this->id = $seed->id;
         $this->book = $seed->book;
         $this->author = $seed->author;
         $this->create_time = $seed->create_time;
         $this->edit_time = $seed->edit_time;
         $this->reference_date = $seed->deliver_date;
         $this->is_frozen = $seed->is_frozen;
         $this->tags = explode(',', $seed->keywords);
         $this->series = $seed->series;
         $this->caption = $seed->title;
         $this->content_type = $seed->section_title;
         $this->thumb = $seed->lede;
         $this->path = $seed->text;
     }
 }
Example #19
0
 /**
  * 获得数据列表
  */
 public function doDefault(ZOL_Request $input, ZOL_Response $output)
 {
     $wArr = array();
     #搜索字段
     $whereSql = "";
     $page = (int) $input->get('page') < 1 ? 1 : (int) $input->get('page');
     $output->sername = $wArr['name'] = $input->get('name');
     if (!empty($wArr)) {
         foreach ($wArr as $k => $v) {
             if (gettype($v) == 'string') {
                 $whereSql .= !empty($v) ? ' AND ' . $k . ' like binary "%' . $v . '%" ' : '';
             } else {
                 $whereSql .= !empty($v) ? ' AND ' . $k . '=' . $v : '';
             }
         }
     }
     $pageUrl = "?c={$output->ctlName}&a={$output->actName}&page={$page}&name={$wArr['name']}";
     $pageSize = 30;
     $orderSql = "order by id desc";
     $data = Helper_Dao::getList(array('dbName' => "Db_Andyou", 'tblName' => "staffcate", 'cols' => "*", 'pageSize' => $pageSize, 'page' => $page, 'pageUrl' => $pageUrl, 'whereSql' => $whereSql, 'orderSql' => $orderSql, 'iswrite' => true, 'pageTpl' => 9));
     if ($data) {
         $output->pageBar = $data['pageBar'];
         $output->allCnt = $data['allCnt'];
         $output->data = $data['data'];
         $output->pageUrl = $pageUrl;
     }
     $output->setTemplate('StaffCate');
 }
Example #20
0
function getTypeName($val, $argument = null)
{
    $type = gettype($val);
    global $detectDateMode;
    switch ($type) {
        case "string":
            if ($detectDateMode == 1 && isDate($val)) {
                return "Date";
            } else {
                if ($detectDateMode == 2 && (bool) strtotime($val)) {
                    return "Date";
                } else {
                    return "String";
                }
            }
        case "integer":
            return "int";
        case "double":
            return "float";
        case "boolean":
            return "boolean";
        case "array":
            if (is_numeric(key($val))) {
                return "RealmList<" . $argument . ">";
            } else {
                return $argument;
            }
    }
    return null;
}
Example #21
0
 /**
  * @internal
  *
  * @param Oxygen_Http_Request     $request
  * @param Oxygen_Util_RequestData $requestData
  * @param string                  $className
  * @param string                  $method
  * @param array                   $actionParameters
  *
  * @return Oxygen_Http_Response
  * @throws Oxygen_Exception
  */
 public function handleRaw($request, $requestData, $className, $method, array $actionParameters)
 {
     $reflectionMethod = new ReflectionMethod($className, $method);
     $parameters = $reflectionMethod->getParameters();
     $arguments = array();
     foreach ($parameters as $parameter) {
         if (isset($actionParameters[$parameter->getName()])) {
             $arguments[] = $actionParameters[$parameter->getName()];
         } else {
             if (!$parameter->isOptional()) {
                 throw new Oxygen_Exception(Oxygen_Exception::ACTION_ARGUMENT_NOT_PROVIDED);
             }
             $arguments[] = $parameter->getDefaultValue();
         }
     }
     if (is_subclass_of($className, 'Oxygen_Container_ServiceLocatorAware')) {
         $instance = call_user_func(array($className, 'createFromContainer'), $this->container);
     } else {
         $instance = new $className();
     }
     $result = call_user_func_array(array($instance, $method), $arguments);
     if (is_array($result)) {
         $result = $this->convertResultToResponse($request, $requestData, $result);
     } elseif (!$result instanceof Oxygen_Http_Response) {
         throw new LogicException(sprintf('An action should return array or an instance of Oxygen_Http_Response; %s gotten.', gettype($result)));
     }
     return $result;
 }
/**
 * Replace property_exists()
 *
 * @category    PHP
 * @package     PHP_Compat
 * @license     LGPL - http://www.gnu.org/licenses/lgpl.html
 * @copyright   2004-2007 Aidan Lister <*****@*****.**>, Arpad Ray <*****@*****.**>
 * @link        http://php.net/property_exists
 * @author      Christian Stadler <*****@*****.**>
 * @version     $Revision: 269597 $
 * @since       PHP 5.1.0
 * @require     PHP 4.0.0 (user_error)
 */
function php_compat_property_exists($class, $property)
{
    if (!is_string($property)) {
        user_error('property_exists() expects parameter 2 to be a string, ' . gettype($property) . ' given', E_USER_WARNING);
        return false;
    }
    if (is_object($class) || is_string($class)) {
        if (is_string($class)) {
            if (!class_exists($class)) {
                return false;
            }
            $vars = get_class_vars($class);
        } else {
            $vars = get_object_vars($class);
        }
        // Bail out early if get_class_vars or get_object_vars didnt work
        // or returned an empty array
        if (!is_array($vars) || count($vars) <= 0) {
            return false;
        }
        $property = strtolower($property);
        foreach (array_keys($vars) as $varname) {
            if (strtolower($varname) == $property) {
                return true;
            }
        }
        return false;
    }
    user_error('property_exists() expects parameter 1 to be a string or ' . 'an object, ' . gettype($class) . ' given', E_USER_WARNING);
    return false;
}
Example #23
0
function debugPrint($var, $file = '')
{
    $more_info = '';
    if (is_string($var)) {
        $more_info = 'size: ' . strlen($var);
    } elseif (is_bool($var)) {
        $more_info = 'val: ' . ($var ? 'true' : 'false');
    } elseif (is_null($var)) {
        $more_info = 'is null';
    } elseif (is_array($var)) {
        $more_info = count($var);
    }
    if ($file === true) {
        $file = '/tmp/logDebug';
    }
    if (strlen($file) > 0) {
        $f = fopen($file, "a");
        ob_start();
        echo date("Y/m/d H:i:s") . " (" . gettype($var) . ") " . $more_info . "\n";
        print_r($var);
        echo "\n\n";
        $output = ob_get_clean();
        fprintf($f, "%s", $output);
        fclose($f);
    } else {
        echo "<pre>" . date("Y/m/d H:i:s") . " (" . gettype($var) . ") " . $more_info . "</pre>";
        echo "<pre>";
        print_r($var);
        echo "</pre>";
    }
}
 /**
  * Validate the plugin
  *
  * Checks that the Model is an instance of ModelInterface
  *
  * @param  mixed $plugin
  * @throws InvalidPluginException
  * @return void
  */
 public function validatePlugin($plugin)
 {
     if ($plugin instanceof ModelInterface) {
         return;
     }
     throw new InvalidPluginException(sprintf('Plugin of type %s is invalid; must implement %s\\Model\\ModelInterface', is_object($plugin) ? get_class($plugin) : gettype($plugin), __NAMESPACE__));
 }
Example #25
0
 /**
  * Converts 2 dimensional data into CSV formatted string
  * 
  * @param array|Traversable data
  * @param column separator
  * @param line ending
  */
 public static function fromData($data, $separator = ',', $lineEnding = "\n")
 {
     if (!is_array($data) && !$data instanceof Traversable) {
         throw new Nette\InvalidArgumentException("Data has to be 2 dimensional array or Traversable object, " . (is_object($data) ? get_class($data) : gettype($data)) . " given.");
     }
     $output = "";
     $lineSep = false;
     foreach ($data as $line) {
         if (!is_array($line) && !$line instanceof Traversable) {
             throw new Nette\InvalidArgumentException("Data has to be 2 dimensional array or Traversable object, " . (is_object($line) ? get_class($line) : gettype($line)) . " has been read as line.");
         }
         if ($lineSep) {
             $output .= $lineEnding;
         } else {
             $lineSep = true;
         }
         $fieldSep = false;
         foreach ($line as $field) {
             $needQuote = false;
             for ($i = 0; $i < strlen($field); $i++) {
                 if (in_array($field[$i], array($separator, "\"", "\r", "\n"))) {
                     $needQuote = true;
                     break;
                 }
             }
             if ($fieldSep) {
                 $output .= $separator;
             } else {
                 $fieldSep = true;
             }
             $output .= $needQuote ? "\"" . str_replace("\"", "\"\"", $field) . "\"" : $field;
         }
     }
     return $output;
 }
Example #26
0
 /**
  * @param int      $expectedType     Expected triggered error type (pass one of PHP's E_* constants)
  * @param string[] $expectedMessages Expected error messages
  * @param callable $testCode         A callable that is expected to trigger the error messages
  */
 public static function assertErrorsAreTriggered($expectedType, $expectedMessages, $testCode)
 {
     if (!is_callable($testCode)) {
         throw new \InvalidArgumentException(sprintf('The code to be tested must be a valid callable ("%s" given).', gettype($testCode)));
     }
     $e = null;
     $triggeredMessages = array();
     try {
         $prevHandler = set_error_handler(function ($type, $message, $file, $line, $context) use($expectedType, &$triggeredMessages, &$prevHandler) {
             if ($expectedType !== $type) {
                 return null !== $prevHandler && call_user_func($prevHandler, $type, $message, $file, $line, $context);
             }
             $triggeredMessages[] = $message;
         });
         call_user_func($testCode);
     } catch (\Exception $e) {
     } catch (\Throwable $e) {
     }
     restore_error_handler();
     if (null !== $e) {
         throw $e;
     }
     \PHPUnit_Framework_Assert::assertCount(count($expectedMessages), $triggeredMessages);
     foreach ($triggeredMessages as $i => $message) {
         \PHPUnit_Framework_Assert::assertContains($expectedMessages[$i], $message);
     }
 }
Example #27
0
 public function addOptions(array $options)
 {
     foreach ($options as $key => $option) {
         if (is_object($option)) {
             if (!$option instanceof Option) {
                 throw new Exception('An option is not valid for option factory. It should be an instance of Option, ' . 'instead an instance of ' . get_class($option) . ' was given');
             }
         } elseif (is_array($option)) {
             if (!is_string($key)) {
                 throw new Exception('An option is not valid for option factory.When the value is an array ' . 'then the key should be a string that represents the name of the optgroup');
             } else {
                 $option = new OptGroup($key, $option);
             }
         } else {
             if (!is_string($option)) {
                 throw new Exception('An option is not valid for option factory. It should be a string, ' . 'instead ' . gettype($option) . ' was given');
             }
             if (is_int($key)) {
                 $option = new Option($option, $option);
             } elseif (is_string($key)) {
                 $option = new Option($option, $key);
             }
         }
         $this->addOption($option);
     }
 }
Example #28
0
 /**
  * Process the provided chain with the data given
  *
  * @param \SalesforceEng\Breakout\Tag $tagInstance Tag
  * @param mixed $data Data to process
  * @return mixed Data result from processing
  */
 public static function resolveValue($data, $path)
 {
     $parts = explode('.', $path);
     $chain = [];
     foreach ($parts as $part) {
         $type = strpos($part, ')') !== false && strpos($part, '(') !== false ? 'function' : 'other';
         $chain[] = ['name' => $part, 'type' => $type];
     }
     $current = null;
     if (isset($data[$path])) {
         return $data[$path];
     }
     foreach ($chain as $item) {
         if ($current === null) {
             $current = $data;
         }
         $name = $item['name'];
         $type = $item['type'];
         $currentType = gettype($current);
         if ($currentType === 'array') {
             if (isset($current[$name])) {
                 $current = $current[$name];
             } else {
                 // If we can't find the data we need, null it out
                 return null;
             }
         } elseif ($currentType === 'object') {
             $current = self::handleObject($current, $item);
         }
     }
     return $current;
 }
Example #29
0
 /**
  * Constructor
  *
  * Prevent creating instances of this class by making the constructor private
  */
 public function __construct(ObjectConfig $config)
 {
     //Set the class loader
     if (!$config->class_loader instanceof ClassLoaderInterface) {
         throw new \InvalidArgumentException('class_loader [ClassLoaderInterface] config option is required, "' . gettype($config->class_loader) . '" given.');
     } else {
         $this->setClassLoader($config['class_loader']);
     }
     //Create the object registry
     if ($config->cache_enabled) {
         $this->_registry = new ObjectRegistryCache();
         $this->_registry->setCachePrefix($config->cache_prefix);
     } else {
         $this->_registry = new ObjectRegistry();
     }
     //Create the object identifier
     $this->__object_identifier = $this->getIdentifier('lib:object.manager');
     //Manually register the library loader
     $config = new ObjectConfig(array('object_manager' => $this, 'object_identifier' => new ObjectIdentifier('lib:object.locator.library')));
     $this->registerLocator(new ObjectLocatorLibrary($config));
     //Register the component locator
     $this->registerLocator('lib:object.locator.component');
     //Register self and set a 'manager' alias
     $this->setObject('lib:object.manager', $this);
     $this->registerAlias('manager', 'lib:object.manager');
 }
 /**
  * @param string $expected Expected type
  * @param mixed $value Received value
  * @param boolean $native Expected a native type?
  * @param \Exception $previous
  */
 public function __construct($expected, $value, $native = false, \Exception $previous = null)
 {
     $valType = is_object($value) ? get_class($value) . ' instance' : gettype($value);
     $expType = $expected . ($native ? ' value' : ' instance');
     $message = sprintf('Expected %s, but received %s', $expType, $valType);
     parent::__construct($message, 0, $previous);
 }