/** * Returns the result of filtering $value * * @param mixed $value * @return mixed */ public function filter($value) { $unfilteredValue = $value; if (is_float($value) && !is_nan($value) && !is_infinite($value)) { ErrorHandler::start(); $formatter = $this->getFormatter(); $currencyCode = $this->setupCurrencyCode(); $result = $formatter->formatCurrency($value, $currencyCode); ErrorHandler::stop(); // FIXME: verify that this, given the initial IF condition, never happens // if ($result === false) { // return $unfilteredValue; // } // Retrieve the precision internally used by the formatter (i.e., depends from locale and currency code) $precision = $formatter->getAttribute(\NumberFormatter::FRACTION_DIGITS); // $result is considered valid if the currency's fraction digits can accomodate the $value decimal precision // i.e. EUR (fraction digits = 2) must NOT allow double(1.23432423432) $isFloatScalePrecise = $this->isFloatScalePrecise($value, $precision, $this->formatter->getAttribute(\NumberFormatter::ROUNDING_MODE)); if ($this->getScaleCorrectness() && !$isFloatScalePrecise) { return $unfilteredValue; } return $result; } return $unfilteredValue; }
public function execute(InputInterface $input, OutputInterface $output) { $cacheDir = $this->config['directory']; if (!is_writable($cacheDir)) { throw new \RuntimeException("Unable to write to the {$cacheDir} directory"); } $output->writeln('<info>Clearing the cache</info>'); $dirIterator = new \RecursiveDirectoryIterator($cacheDir, \FilesystemIterator::SKIP_DOTS); /** @var \DirectoryIterator[] $items */ $items = new \RecursiveIteratorIterator($dirIterator, \RecursiveIteratorIterator::CHILD_FIRST); foreach ($items as $item) { if (substr($item->getFileName(), 0, 1) == '.') { continue; } if ($item->isFile()) { ErrorHandler::start(); unlink($item->getPathName()); ErrorHandler::stop(true); if (file_exists($item->getPathname())) { throw new \RuntimeException('Could not delete file ' . $item->getPathname()); } } else { ErrorHandler::start(); rmdir($item->getPathName()); ErrorHandler::stop(true); if (file_exists($item->getPathname())) { throw new \RuntimeException('Could not delete directory ' . $item->getPathname()); } } } $output->writeln('Successfully deleted all cache files'); }
public function onRun(RunEvent $e) { /* @var $test \ZFTool\Diagnostics\Test\TestInterface */ $test = $e->getTarget(); try { ErrorHandler::start($this->getCatchErrorSeverity()); $result = $test->run(); ErrorHandler::stop(true); } catch (ErrorException $e) { return new Failure('PHP ' . static::getSeverityDescription($e->getSeverity()) . ': ' . $e->getMessage(), $e); } catch (\Exception $e) { ErrorHandler::stop(false); return new Failure('Uncaught ' . get_class($e) . ': ' . $e->getMessage(), $e); } // Check if we've received a Result object if (is_object($result)) { if (!$result instanceof ResultInterface) { return new Failure('Test returned unknown object ' . get_class($result), $result); } return $result; // Interpret boolean as a failure or success } elseif (is_bool($result)) { if ($result) { return new Success(); } else { return new Failure(); } // Convert scalars to a warning } elseif (is_scalar($result)) { return new Warning('Test returned unexpected ' . gettype($result), $result); // Otherwise interpret as failure } else { return new Failure('Test returned unknown result of type ' . gettype($result), $result); } }
public function pharAction() { $client = $this->serviceLocator->get('zendServerClient'); $client = new Client(); if (defined('PHAR')) { // the file from which the application was started is the phar file to replace $file = $_SERVER['SCRIPT_FILENAME']; } else { $file = dirname($_SERVER['SCRIPT_FILENAME']) . '/zs-client.phar'; } $request = new Request(); $request->setMethod(Request::METHOD_GET); $request->setHeaders(Headers::fromString('If-Modified-Since: ' . gmdate('D, d M Y H:i:s T', filemtime($file)))); $request->setUri('https://github.com/zendtech/ZendServerSDK/raw/master/bin/zs-client.phar'); //$client->getAdapter()->setOptions(array('sslcapath' => __DIR__.'/../../../certs/')); $client->setAdapter(new Curl()); $response = $client->send($request); if ($response->getStatusCode() == 304) { return 'Already up-to-date.'; } else { ErrorHandler::start(); rename($file, $file . '.' . date('YmdHi') . '.backup'); $handler = fopen($file, 'w'); fwrite($handler, $response->getBody()); fclose($handler); ErrorHandler::stop(true); return 'The phar file was updated successfully.'; } }
/** * Load a CSV file content * * {@inheritdoc} * @return TextDomain|false */ public function load($locale, $filename) { //$filename .= $this->fileExtension; $messages = array(); ErrorHandler::start(); $file = fopen($filename, 'rb'); $error = ErrorHandler::stop(); if (false === $file) { return false; } while (($data = fgetcsv($file, $this->options['length'], $this->options['delimiter'], $this->options['enclosure'])) !== false) { if (substr($data[0], 0, 1) === '#') { continue; } if (!isset($data[1])) { continue; } if (count($data) == 2) { $messages[$data[0]] = $data[1]; } else { $singular = array_shift($data); $messages[$singular] = $data; } } $textDomain = new TextDomain($messages); return $textDomain; }
/** * Open connection to IMAP server * * @param string $host hostname or IP address of IMAP server * @param int|null $port of IMAP server, default is 143 (993 for ssl) * @param string|bool $ssl use 'SSL', 'TLS' or false * @throws Exception\RuntimeException * @return string welcome message */ public function connect($host, $port = null, $ssl = false) { if ($ssl == 'SSL') { $host = 'ssl://' . $host; } if ($port === null) { $port = $ssl === 'SSL' ? 993 : 143; } ErrorHandler::start(); $this->socket = fsockopen($host, $port, $errno, $errstr, self::TIMEOUT_CONNECTION); $error = ErrorHandler::stop(); if (!$this->socket) { throw new Exception\RuntimeException(sprintf( 'cannot connect to host%s', ($error ? sprintf('; error = %s (errno = %d )', $error->getMessage(), $error->getCode()) : '') ), 0, $error); } if (!$this->_assumedNextLine('* OK')) { throw new Exception\RuntimeException('host doesn\'t allow connection'); } if ($ssl === 'TLS') { $result = $this->requestAndResponse('STARTTLS'); $result = $result && stream_socket_enable_crypto($this->socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); if (!$result) { throw new Exception\RuntimeException('cannot enable TLS'); } } }
/** * Constructor * * @param string|resource|array|Traversable $streamOrUrl Stream or URL to open as a stream * @param string|null $mode Mode, only applicable if a URL is given * @param null|string $logSeparator Log separator string * @return Stream * @throws Exception\InvalidArgumentException * @throws Exception\RuntimeException */ public function __construct($streamOrUrl, $mode = null, $logSeparator = null) { if ($streamOrUrl instanceof Traversable) { $streamOrUrl = iterator_to_array($streamOrUrl); } if (is_array($streamOrUrl)) { $mode = isset($streamOrUrl['mode']) ? $streamOrUrl['mode'] : null; $logSeparator = isset($streamOrUrl['log_separator']) ? $streamOrUrl['log_separator'] : null; $streamOrUrl = isset($streamOrUrl['stream']) ? $streamOrUrl['stream'] : null; } // Setting the default mode if (null === $mode) { $mode = 'a'; } if (is_resource($streamOrUrl)) { if ('stream' != get_resource_type($streamOrUrl)) { throw new Exception\InvalidArgumentException(sprintf('Resource is not a stream; received "%s', get_resource_type($streamOrUrl))); } if ('a' != $mode) { throw new Exception\InvalidArgumentException(sprintf('Mode must be "a" on existing streams; received "%s"', $mode)); } $this->stream = $streamOrUrl; } else { ErrorHandler::start(); $this->stream = fopen($streamOrUrl, $mode, false); $error = ErrorHandler::stop(); if (!$this->stream) { throw new Exception\RuntimeException(sprintf('"%s" cannot be opened with mode "%s"', $streamOrUrl, $mode), 0, $error); } } if (null !== $logSeparator) { $this->setLogSeparator($logSeparator); } $this->formatter = new SimpleFormatter(); }
/** * @param string $fileName * @return \Application\SharedKernel\SqliteDbFile */ public static function initializeFromDist($fileName) { $dist = new self($fileName . '.dist'); ErrorHandler::start(); copy($dist->toString(), $fileName); ErrorHandler::stop(true); return new self($fileName); }
public function tearDown() { // be sure the error handler has been stopped if (ErrorHandler::started()) { ErrorHandler::stop(); $this->fail('ErrorHandler not stopped'); } }
/** * Object destructor. * * Closes the file if it had been successfully opened. */ public function __destruct() { if (is_resource($this->_fileResource)) { ErrorHandler::start(E_WARNING); fclose($this->_fileResource); ErrorHandler::stop(); } }
public function testSetByValueException() { /* @var $style \ZfcDatagrid\Column\Style\AbstractStyle */ $style = $this->getMockForAbstractClass('ZfcDatagrid\\Column\\Style\\AbstractStyle'); ErrorHandler::start(E_USER_DEPRECATED); $style->setByValue($this->column, 'test'); $err = ErrorHandler::stop(); $this->assertInstanceOf('ErrorException', $err); }
public function checkForErrors(MvcEvent $e) { try { ErrorHandler::stop(true); $this->startMonitoringErrors($e); } catch (ErrorException $exception) { $this->outputFatalError($exception, $e); } return; }
/** * {@inheritDoc} */ public function remove($key) { ErrorHandler::start(\E_WARNING); $success = unlink($this->cachedFile()); ErrorHandler::stop(); if (false === $success) { throw new RuntimeException(sprintf('Could not remove key "%s"', $this->cachedFile())); } return $success; }
/** * @inheritdoc * @throws \RuntimeException */ public function download($id, FileInterface $output) { $source = new GFile($id, $this->filesystem); ErrorHandler::start(); $flag = file_put_contents($output->getPath(), $source->getContent()); ErrorHandler::stop(true); if ($flag === false) { throw new \RuntimeException("Could not download file ({$id})"); } }
/** * @todo Remove error handling once we remove deprecation warning from getConstants method */ public function testGetConstantsReturnsConstantNames() { $file = new FileScanner(__DIR__ . '/../TestAsset/FooClass.php'); $class = $file->getClass('ZendTest\\Code\\TestAsset\\FooClass'); ErrorHandler::start(E_USER_DEPRECATED); $constants = $class->getConstants(); $error = ErrorHandler::stop(); $this->assertInstanceOf('ErrorException', $error); $this->assertContains('FOO', $constants); }
/** * Object constructor * * @throws \ZendSearch\Lucene\Exception\RuntimeException */ public function __construct() { ErrorHandler::start(E_WARNING); $result = preg_match('/\\pL/u', 'a'); ErrorHandler::stop(); if ($result != 1) { // PCRE unicode support is turned off throw new RuntimeException('Utf8 analyzer needs PCRE unicode support to be enabled.'); } }
/** * Constructor * * Attempts to read from php://input to get raw POST request; if an error * occurs in doing so, or if the XML is invalid, the request is declared a * fault. * */ public function __construct() { ErrorHandler::start(); $xml = file_get_contents('php://input'); ErrorHandler::stop(); if (!$xml) { $this->fault = new Fault(630); return; } $this->xml = $xml; $this->loadXml($xml); }
/** * @param string $configLocation * @param string $sqliteDbFile * @return EventStoreSetUpWasUndone */ public static function undoEventStoreSetUp($configLocation, $sqliteDbFile) { ErrorHandler::start(); if (file_exists($configLocation . DIRECTORY_SEPARATOR . self::$configFileName)) { unlink($configLocation . DIRECTORY_SEPARATOR . self::$configFileName); } if (file_exists($sqliteDbFile)) { unlink($sqliteDbFile); } ErrorHandler::stop(); return EventStoreSetUpWasUndone::in($configLocation . DIRECTORY_SEPARATOR . self::$configFileName); }
/** * @return bool */ public static function hasPcreUnicodeSupport() { if (static::$hasPcreUnicodeSupport === null) { static::$hasPcreUnicodeSupport = false; ErrorHandler::start(); if (defined('PREG_BAD_UTF8_OFFSET_ERROR') || preg_match('/\\pL/u', 'a') == 1) { static::$hasPcreUnicodeSupport = true; } ErrorHandler::stop(); } return static::$hasPcreUnicodeSupport; }
/** * Deserialize igbinary string to PHP value * * @param string $serialized * @return mixed * @throws Exception\RuntimeException on igbinary error */ public function unserialize($serialized) { if ($serialized === static::$serializedNull) { return null; } ErrorHandler::start(); $ret = igbinary_unserialize($serialized); $err = ErrorHandler::stop(); if ($ret === null) { throw new Exception\RuntimeException('Unserialization failed', 0, $err); } return $ret; }
/** * Override moveUploadedFile * * If the request is not HTTP, or not a PUT or PATCH request, delegates to * the parent functionality. * * Otherwise, does a `rename()` operation, and returns the status of the * operation. * * @param string $sourceFile * @param string $targetFile * @return bool * @throws FilterRuntimeException in the event of a warning */ protected function moveUploadedFile($sourceFile, $targetFile) { if (null === $this->request || !method_exists($this->request, 'isPut') || !$this->request->isPut() && !$this->request->isPatch()) { return parent::moveUploadedFile($sourceFile, $targetFile); } ErrorHandler::start(); $result = rename($sourceFile, $targetFile); $warningException = ErrorHandler::stop(); if (false === $result || null !== $warningException) { throw new FilterRuntimeException(sprintf('File "%s" could not be renamed. An error occurred while processing the file.', $sourceFile), 0, $warningException); } return $result; }
/** * Retrieve a cached SMD * * On success, returns the cached SMD (a JSON string); an failure, returns * boolean false. * * @param string $filename * @return string|false */ public static function getSmd($filename) { if (!is_string($filename) || !file_exists($filename) || !is_readable($filename)) { return false; } ErrorHandler::start(); $smd = file_get_contents($filename); ErrorHandler::stop(); if (false === $smd) { return false; } return $smd; }
/** * Deserialize msgpack string to PHP value * * @param string $serialized * @return mixed * @throws Exception\RuntimeException on msgpack error */ public function unserialize($serialized) { if ($serialized === static::$serialized0) { return 0; } ErrorHandler::start(); $ret = msgpack_unserialize($serialized); $err = ErrorHandler::stop(); if ($ret === 0) { throw new Exception\RuntimeException('Unserialization failed', 0, $err); } return $ret; }
/** * @param string $sImagePath * @see \AssetsBundle\Service\Filter\FilterInterface::run() * @throws \InvalidArgumentException * @throws \RuntimeException * @return string */ public function filterAssetFile(\AssetsBundle\AssetFile\AssetFile $oAssetFile) { //If asset file should not be optimize, return current content if (!$this->assetFileShouldBeOptimize($oAssetFile)) { return $oAssetFile->getAssetFileContents(); } //Optimize image \Zend\Stdlib\ErrorHandler::start(); $oImage = imagecreatefromstring($oAssetFile->getAssetFileContents()); imagealphablending($oImage, false); imagesavealpha($oImage, true); \Zend\Stdlib\ErrorHandler::stop(true); return $this->optimizeImage($oImage); }
/** * Defined by Zend\Filter\FilterInterface * * @see Zend\Filter\FilterInterface::filter() * @param mixed $value * @return mixed */ public function filter($value) { if (!is_int($value) && !is_float($value)) { $result = parent::filter($value); } else { ErrorHandler::start(); $result = $this->getFormatter()->format($value, $this->getType()); ErrorHandler::stop(); } if (false !== $result) { return str_replace(" ", ' ', $result); } return $value; }
public function __construct($directory) { $this->directory = rtrim($directory, '/'); if (is_dir($directory) && !is_writable($directory)) { throw new RuntimeException("Unable to write to the target directory ({$directory})"); } elseif (file_exists($directory) && !is_dir($directory)) { throw new RuntimeException("Target must be a directory ({$directory})"); } if (!is_dir($directory)) { ErrorHandler::start(); mkdir($directory, 0770, true); ErrorHandler::stop(true); } }
/** * @param $regExIdentifier * @return $this * @throws InvalidArgumentException */ public function setRegExIdentifier($regExIdentifier) { ErrorHandler::start(); $result = preg_match($regExIdentifier, static::RENDITION_SEPARATOR); $error = ErrorHandler::stop(); if ($result === false) { throw new InvalidArgumentException(sprintf('Internal error parsing the regExIdentifier ("%s")', $regExIdentifier), 0, $error); } if ($result == 0) { $this->regExIdentifier = $regExIdentifier; return $this; } throw new InvalidArgumentException(sprintf('The identifier regex can not match the rendition separator ("%s")', static::RENDITION_SEPARATOR)); }
public function indexAction() { $request = $this->getRequest(); /* @var $request \Zend\Console\Request */ $path = $request->getParam('path', getcwd() . '/supervisord.conf'); if (substr($path, 0, 1) != '/') { $path = getcwd() . '/' . $path; } // @todo: do not parse config, but use the plugin managers instead, see: getRegisteredServices() $config = $this->getServiceLocator()->get('Config'); $moduleConfig = $config['humus_amqp_module']; $supervisordConfig = $config['humus_supervisor_module']['humus-amqp-supervisor']['supervisord']; $consumerTypes = array('consumers', 'rpc_servers'); $config = new Configuration(); $section = new SupervisordSection($supervisordConfig['config']); $config->addSection($section); $section = new RpcInterfaceSection('supervisor', $supervisordConfig['rpcinterface']); $config->addSection($section); $section = new SupervisorctlSection($supervisordConfig['supervisorctl']); $config->addSection($section); $section = new UnixHttpServerSection($supervisordConfig['unix_http_server']); $config->addSection($section); $section = new InetHttpServerSection($supervisordConfig['inet_http_server']); $config->addSection($section); foreach ($consumerTypes as $consumerType) { $partConfig = $moduleConfig[$consumerType]; // no config found, check next one if (empty($partConfig)) { continue; } foreach ($partConfig as $name => $part) { $section = new ProgramSection($name, array('process_name' => '%(program_name)s_%(host_node_name)s_%(process_num)02d', 'directory' => getcwd(), 'autostart' => true, 'autorestart' => true, 'numprocs' => 1, 'command' => 'php public/index.php humus amqp ' . str_replace('_', '-', strtolower(substr($consumerType, 0, -1))) . ' ' . $name)); if (isset($part['supervisord']) && is_array($part['supervisord'])) { $options = array_merge($section->getOptions(), $part['supervisord']); $section->setOptions($options); } $config->addSection($section); } } ErrorHandler::start(); $rs = file_put_contents($path, $config->render()); $error = ErrorHandler::stop(); if (false === $rs || $error) { $this->getConsole()->writeLine('ERROR: Cannot write configuration to ' . $path, ColorInterface::RED); return null; } $this->getConsole()->writeLine('OK: configuration written to ' . $path, ColorInterface::GREEN); return null; }
/** * Serialize PHP to WDDX * * @param mixed $value * @return string * @throws Exception\RuntimeException on wddx error */ public function serialize($value) { $comment = $this->getOptions()->getComment(); ErrorHandler::start(); if ($comment !== '') { $wddx = wddx_serialize_value($value, $comment); } else { $wddx = wddx_serialize_value($value); } $error = ErrorHandler::stop(); if ($wddx === false) { throw new Exception\RuntimeException('Serialization failed', 0, $error); } return $wddx; }
/** * @param $buffer * @return string|null */ protected function detectBufferMimeType($buffer) { $type = null; if (function_exists('finfo_open')) { if (static::$fileInfoDb === null) { ErrorHandler::start(); static::$fileInfoDb = finfo_open(FILEINFO_MIME_TYPE); ErrorHandler::stop(); } if (static::$fileInfoDb) { $type = finfo_buffer(static::$fileInfoDb, $buffer, FILEINFO_MIME_TYPE); } } return $type; }