/** * easier to program for a list of keys passed in and returned, than the overloaded interface * of the normal get method. */ protected function getMulti(array $request) { $map = array(); $shards = array(); foreach ($request as $k) { $shard = $this->shard($k); $hash = spl_object_hash($shard); $shards[$hash] = $shard; if (!isset($map[$hash])) { $map[$hash] = array(); } $map[$hash][] = $k; } $rows = array(); $rows = array_fill_keys($request, NULL); foreach ($map as $hash => $keys) { $shard = $shards[$hash]; foreach ($shard->get($keys) as $k => $v) { $rows[$k] = $v; } } foreach ($rows as $k => $v) { if ($v === NULL) { unset($rows[$k]); } } return $rows; }
/** * 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]; }
/** * @param \stdClass $object */ function it_wraps_non_token_arguments_into_ExactValueToken($object) { $this->beConstructedWith(array(42, 'zet', $object)); $class = get_class($object->getWrappedObject()); $hash = spl_object_hash($object->getWrappedObject()); $this->__toString()->shouldReturn("exact(42), exact(\"zet\"), exact({$class}:{$hash} Object (\n 'objectProphecy' => Prophecy\\Prophecy\\ObjectProphecy Object (*Prophecy*)\n))"); }
/** * Connects the TeamSpeak3_Transport_Abstract object and performs initial actions on the remote * server. * * @throws TeamSpeak3_Adapter_Exception * @return void */ public function syn() { $this->initTransport($this->options); $this->transport->setAdapter($this); TeamSpeak3_Helper_Profiler::init(spl_object_hash($this)); TeamSpeak3_Helper_Signal::getInstance()->emit("filetransferConnected", $this); }
/** * Stringifies any provided value. * * @param mixed $value * @param boolean $exportObject * * @return string */ public function stringify($value, $exportObject = true) { if (is_array($value)) { if (range(0, count($value) - 1) === array_keys($value)) { return '[' . implode(', ', array_map(array($this, __FUNCTION__), $value)) . ']'; } $stringify = array($this, __FUNCTION__); return '[' . implode(', ', array_map(function ($item, $key) use($stringify) { return (is_integer($key) ? $key : '"' . $key . '"') . ' => ' . call_user_func($stringify, $item); }, $value, array_keys($value))) . ']'; } if (is_resource($value)) { return get_resource_type($value) . ':' . $value; } if (is_object($value)) { return $exportObject ? ExportUtil::export($value) : sprintf('%s:%s', get_class($value), spl_object_hash($value)); } if (true === $value || false === $value) { return $value ? 'true' : 'false'; } if (is_string($value)) { $str = sprintf('"%s"', str_replace("\n", '\\n', $value)); if (50 <= strlen($str)) { return substr($str, 0, 50) . '"...'; } return $str; } if (null === $value) { return 'null'; } return (string) $value; }
public function detachShared(SharedEventManagerInterface $events) { foreach ($this->listeners[\spl_object_hash($events)] as $listener) { $events->detach($this->identity, $listener); } return __METHOD__; }
/** * Creates a string hash for a value * * @param mixed $value The value * @param string $algo The hash algorithm * * @return string */ public static function hash($value, string $algo = 'fnv1a32') : string { $type = gettype($value); switch ($type) { case 'object': if (Validate::isEquatable($value)) { $string = sprintf('e_%s', $value->hashValue()); } else { $string = sprintf('o_%s', spl_object_hash($value)); } break; case 'string': $string = sprintf('s_%s', $value); break; case 'integer': $string = sprintf('i_%d', $value); break; case 'double': $string = sprintf('f_%.14F', $value); break; case 'boolean': $string = sprintf('b_%d', (int) $value); break; case 'resource': $string = sprintf('r_%d', (int) $value); break; case 'array': $string = sprintf('a_%s', serialize($value)); break; default: $string = '0'; break; } return hash($algo, $string); }
public function endTest(\PHPUnit_Framework_Test $test, $time) { if (!in_array(spl_object_hash($test), $this->unsuccessfulTests)) { $this->fire(Events::TEST_SUCCESS, new TestEvent($test)); } $this->dispatcher->dispatch(Events::TEST_END, new TestEvent($test, $time)); }
/** * @param Contact $entity * @param array $options * @return \Devture\Component\Form\Validator\ViolationsList */ public function validate($entity, array $options = array()) { $violations = parent::validate($entity, $options); $name = $entity->getName(); if (strlen($name) < 3 || !preg_match("/^[a-z][a-z0-9_\\-\\.]+\$/", $name)) { $violations->add('name', 'Invalid name.'); } else { try { $ent = $this->repository->findOneBy(array('name' => $name)); if (spl_object_hash($ent) !== spl_object_hash($entity)) { $violations->add('name', 'The name is already in use.'); } } catch (NotFound $e) { } } if (!$entity->getTimePeriod() instanceof TimePeriod) { $violations->add('timePeriod', 'The time period is not valid.'); } if (!$entity->getServiceNotificationCommand() instanceof Command) { $violations->add('serviceNotificationCommand', 'The service notification command is not valid.'); } if ($this->isEmpty($entity->getEmail()) && count($entity->getAddresses()) === 0) { $violations->add('__other__', 'An email address or other addresses need to be entered.'); } foreach ($entity->getAddresses() as $slot => $address) { $slot = (int) $slot; if ($slot < 1 || $slot > Contact::ADDRESS_SLOTS_COUNT) { $violations->add('addresses', 'Slot %slot% is not allowed.', array('%slot%' => $slot)); } } return $violations; }
/** * Returns a string representing the supplied value's identity. * * @param mixed $value * * @return string */ public static function hash($value) { $typeIdentifier = gettype($value)[0]; switch ($typeIdentifier) { case 's': //string return 's' . (strlen($value) > 32 ? md5($value) : $value); case 'i': //integer //integer case 'b': //boolean //boolean case 'd': //double //double case 'r': //resource //resource case 'u': //unknown type return $typeIdentifier . $value; case 'N': //NULL return 'N'; case 'o': //object return 'o' . spl_object_hash($value); case 'a': //array return self::arrayHash($value); } }
public function valuesProvider() { $obj2 = new \stdClass(); $obj2->foo = 'bar'; $obj3 = (object) array(1, 2, "Test\r\n", 4, 5, 6, 7, 8); $obj = new \stdClass(); // @codingStandardsIgnoreStart $obj->null = null; // @codingStandardsIgnoreEnd $obj->boolean = true; $obj->integer = 1; $obj->double = 1.2; $obj->string = '1'; $obj->text = "this\nis\na\nvery\nvery\nvery\nvery\nvery\nvery\rlong\n\rtext"; $obj->object = $obj2; $obj->objectagain = $obj2; $obj->array = array('foo' => 'bar'); $obj->array2 = array(1, 2, 3, 4, 5, 6); $obj->array3 = array($obj, $obj2, $obj3); $obj->self = $obj; $storage = new \SplObjectStorage(); $storage->attach($obj2); $storage->foo = $obj2; return array(array($obj, spl_object_hash($obj)), array($obj2, spl_object_hash($obj2)), array($obj3, spl_object_hash($obj3)), array($storage, spl_object_hash($storage)), array($obj->array, 0), array($obj->array2, 0), array($obj->array3, 0)); }
public function testPartialApplication() { $callback = new Callback('\\Fatso\\Tests\\Util\\CallbackContainer::concat'); $new = $callback->partial('abcd'); $this->assertEquals('abcdEF', $new('EF')); $this->assertNotEquals(spl_object_hash($callback), spl_object_hash($new)); }
/** * Connects the TeamSpeak3_Transport_Abstract object and performs initial actions on the remote * server. * * @throws TeamSpeak3_Adapter_Exception * @return void */ public function syn() { $this->initTransport($this->options); $this->transport->setAdapter($this); \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Profiler::init(spl_object_hash($this)); \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit("filetransferConnected", $this); }
public function testPersistObjects() { $collection = new Collection($this->cursor, true); // collect object hashes from first iterate / hydrate $hashes = []; foreach ($collection as $item) { $hashes[] = spl_object_hash($item); } //iterate the same collection again and we should get the same exact objects back $secondaryHashes = []; foreach ($collection as $item) { $secondaryHashes[] = spl_object_hash($item); } $this->assertEquals(count($hashes), count($secondaryHashes), 'got different number of items during second iteration of collection'); for ($c = 0; $c < count($hashes); $c++) { $this->assertEquals($hashes[$c], $secondaryHashes[$c], 'got different object hashes the second time around'); } // now test that NOT persisting objects results in new objects each time iterated $collection = new Collection($this->cursor); // collect object hashes from first iterate / hydrate $hashes = []; foreach ($collection as $item) { $hashes[] = spl_object_hash($item); } //iterate the same collection again and we should get the NEW objects back $secondaryHashes = []; foreach ($collection as $item) { $secondaryHashes[] = spl_object_hash($item); } $this->assertEquals(count($hashes), count($secondaryHashes), 'got different number of items during second iteration of collection'); for ($c = 0; $c < count($hashes); $c++) { $this->assertNotEquals($hashes[$c], $secondaryHashes[$c], 'got same object hashes the second time around'); } }
public function testInitServiceEvent() { $this->assertEquals('blah blah blah', Dummy::saySomething()); $this->appPkg->addEventListener(Event\Type\System\InitService::toType(), function ($event) { $pkgName = $event->getCurrentNode()->getComposerName(); if ($event->getShortClassName() == 'Dummy') { return function () use($pkgName) { $this->pkgName = $pkgName; $this->sentence = 'I hope it will work'; }; } }); $ext = $this->appPkg->getExtensions()[0]; $this->assertEquals(spl_object_hash($ext), spl_object_hash($this->appPkg->getChildNodes()[0])); // this event handler would not be triggered $ext->addEventListener(Event\Type\System\InitService::toType(), function ($event) { $pkgName = $event->getCurrentNode()->getComposerName(); if ($event->getShortClassName() == 'Dummy') { return function () use($pkgName) { $this->pkgName = $pkgName; $this->sentence = "Wanna sleep"; }; } }); // fire event by creating a service instance $dummy = Dummy::create(); $this->assertEquals('I hope it will work', $dummy->saySomething()); $this->assertEquals('phpcrystal/phpcrystaltest', $dummy->getPackageName()); }
/** * Persists node in given position strategy */ protected function persistAs($node, $child = null, $position = Nested::FIRST_CHILD) { $em = $this->getEntityManager(); $wrapped = new EntityWrapper($node, $em); $meta = $this->getClassMetadata(); $config = $this->listener->getConfiguration($em, $meta->name); $siblingInPosition = null; if ($child !== null) { switch ($position) { case Nested::PREV_SIBLING: case Nested::NEXT_SIBLING: $sibling = new EntityWrapper($child, $em); $newParent = $sibling->getPropertyValue($config['parent']); if (null === $newParent && isset($config['root'])) { throw new UnexpectedValueException("Cannot persist sibling for a root node, tree operation is not possible"); } $siblingInPosition = $child; $child = $newParent; break; } $wrapped->setPropertyValue($config['parent'], $child); } $wrapped->setPropertyValue($config['left'], 0); // simulate changeset $oid = spl_object_hash($node); $this->listener->getStrategy($em, $meta->name)->setNodePosition($oid, $position, $siblingInPosition); $em->persist($node); return $this; }
/** * Test that attaching a log writer adds it to the array of log writers * * @TODO Is this test too specific? * * @test * @covers Kohana_Log::attach */ public function test_attach_attaches_log_writer_and_returns_this() { $logger = new Kohana_Log(); $writer = $this->getMockForAbstractClass('Kohana_Log_Writer'); $this->assertSame($logger, $logger->attach($writer)); $this->assertAttributeSame(array(spl_object_hash($writer) => array('object' => $writer, 'types' => NULL)), '_writers', $logger); }
/** * @return null|string */ public function getAggregateRootId($object) { if (!is_object($object)) { throw new \InvalidArgumentException(); } return $this->aggregateRootIds[spl_object_hash($object)] ?? null; }
/** * Test the cache can be bootstrapped when using the redis driver. * * @covers Molovo\Amnesia\Cache::bootstrap * @covers Molovo\Amnesia\Cache\Instance::__construct * @covers Molovo\Amnesia\Driver\File::__construct * @covers Molovo\Amnesia\Cache::instance */ public function testBootstrap() { $name = 'file_driver_test'; $config = [$name => ['driver' => 'file', 'store_path' => dirname(dirname(__DIR__)) . '/_data/cache/store']]; if (!is_dir($config[$name]['store_path'])) { // This is a test cache, so just let anyone write to it // to avoid having to deal with permissions issues mkdir($config[$name]['store_path'], 0777, true); } Cache::bootstrap($config); $instance = Cache::instance($name); verify($instance)->isInstanceOf(Instance::class); // Test that the driver has been instantiated correctly $property = new \ReflectionProperty(Instance::class, 'driver'); $property->setAccessible(true); $driver = $property->getValue($instance); verify($driver)->isInstanceOf(File::class); // Call a second time to test retrieval from cache $cached_instance = Cache::instance($name); // Compare hashes of the two instances to ensure they are // the same object $hash1 = spl_object_hash($instance); $hash2 = spl_object_hash($cached_instance); verify($hash1)->equals($hash2); // Store the instance so we can use it in other tests static::$instance = $instance; }
public function testGlobalFunctionIsASingelton() { Manager::registerGlobalFunction(); $obj1 = AssetManager(); $obj2 = AssetManager(); $this->assertEquals(spl_object_hash($obj1), spl_object_hash($obj2)); }
public function getCreateQuery($object) { $propertyValues = []; $extraLabels = []; $removeLabels = []; foreach ($this->classMetadata->getPropertiesMetadata() as $field => $meta) { $propertyValues[$field] = $meta->getValue($object); } foreach ($this->classMetadata->getLabeledProperties() as $labeledProperty) { if ($labeledProperty->isLabelSet($object)) { $extraLabels[] = $labeledProperty->getLabelName(); } else { $removeLabels[] = $labeledProperty->getLabelName(); } } $query = sprintf('CREATE (n:%s) SET n += {properties}', $this->classMetadata->getLabel()); if (!empty($extraLabels)) { foreach ($extraLabels as $label) { $query .= ' SET n:' . $label; } } if (!empty($removeLabels)) { foreach ($removeLabels as $label) { $query .= ' REMOVE n:' . $label; } } $query .= ' RETURN id(n) as id'; return Statement::create($query, ['properties' => $propertyValues], spl_object_hash($object)); }
public function testReadOnly() { $this->markTestIncomplete('To be fixed.'); Tests_DBLoader4Test::getUp(); $servCheck = ServerCheck::getInstance(); $allServerParams = $servCheck->getAllServerParams(); $upload = $servCheck->getUploadParams(); $mysql_params = $servCheck->getMysqlParams(); $this->assertEquals($servCheck->getUploadParams(), $allServerParams->getUpload()); $this->assertEquals($upload, $allServerParams->getUpload()); $this->assertNotEquals(spl_object_hash($upload), $allServerParams->getUpload()); $this->assertNotEquals(spl_object_hash($upload), $servCheck->getUploadParams()); $this->setExpectedException('DomainException'); $allServerParams->field_test_not_existent = "kkk"; $this->setExpectedException('Exception'); echo $allServerParams->field_test_not_existent; $this->setExpectedException('DomainException'); $upload->field_test_not_existent = "kkk"; $this->setExpectedException('Exception'); echo $upload->field_test_not_existent; $this->setExpectedException('DomainException'); $mysql_params->field_test_not_existent = "kkk"; $this->setExpectedException('Exception'); echo $mysql_params->field_test_not_existent; }
public function testSPLObjectHashCollisionOnReplacingEmbeddedDoc() { $usedHashes = array(); $owner = new GH1017Document(); $this->dm->persist($owner); $this->dm->flush(); $maxTries = 10; // Keep replacing the embedded object // until the same object hash is returned for ($i = 0; $i < $maxTries; $i++) { unset($owner->embedded); $owner->embedded = new GH1017EmbeddedDocument(); $oid = spl_object_hash($owner->embedded); if (in_array($oid, $usedHashes)) { // Collision found, let's test state of embedded doc $this->assertEquals(UnitOfWork::STATE_NEW, $this->uow->getDocumentState($owner->embedded), 'A newly created object should be treated as NEW by UOW'); return; } $usedHashes[] = $oid; $this->dm->flush(); } // At the time of writing this test, // collision was always found when $i == 2 $this->markTestSkipped('No object hash collision ' . 'encountered after ' . $maxTries . 'tries'); }
public function detach(EventCollection $events) { foreach ($this->handles[\spl_object_hash($events)] as $handle) { $events->detach($handle); } return __METHOD__; }
/** * @param ActiveRecord $record */ public function addUploaded(ActiveRecord $record) { $hash = spl_object_hash($record); if (!isset($this->uploaded[$hash])) { $this->uploaded[$hash] = ['record' => $record]; } }
/** * {@inheritdoc} */ public function extractSubmittedData(FormInterface $form) { $data = array('submitted_data' => array('norm' => $this->valueExporter->exportValue($form->getNormData())), 'errors' => array()); if ($form->getViewData() !== $form->getNormData()) { $data['submitted_data']['view'] = $this->valueExporter->exportValue($form->getViewData()); } if ($form->getData() !== $form->getNormData()) { $data['submitted_data']['model'] = $this->valueExporter->exportValue($form->getData()); } foreach ($form->getErrors() as $error) { $errorData = array('message' => $error->getMessage(), 'origin' => is_object($error->getOrigin()) ? spl_object_hash($error->getOrigin()) : null, 'trace' => array()); $cause = $error->getCause(); while (null !== $cause) { if ($cause instanceof ConstraintViolationInterface) { $errorData['trace'][] = array('class' => $this->valueExporter->exportValue(get_class($cause)), 'root' => $this->valueExporter->exportValue($cause->getRoot()), 'path' => $this->valueExporter->exportValue($cause->getPropertyPath()), 'value' => $this->valueExporter->exportValue($cause->getInvalidValue())); $cause = method_exists($cause, 'getCause') ? $cause->getCause() : null; continue; } if ($cause instanceof \Exception) { $errorData['trace'][] = array('class' => $this->valueExporter->exportValue(get_class($cause)), 'message' => $this->valueExporter->exportValue($cause->getMessage())); $cause = $cause->getPrevious(); continue; } $errorData['trace'][] = $cause; break; } $data['errors'][] = $errorData; } $data['synchronized'] = $this->valueExporter->exportValue($form->isSynchronized()); return $data; }
/** * @param object $entity * @param bool $isFullData * @param bool $isPersistNew * @param mixed|array|null $itemData * @param array $searchContext * @return null|object */ protected function processEntity($entity, $isFullData = false, $isPersistNew = false, $itemData = null, array $searchContext = array()) { $oid = spl_object_hash($entity); if (isset($this->cachedEntities[$oid])) { return $entity; } // find and cache existing or new entity $existingEntity = $this->findExistingEntity($entity, $searchContext); if ($existingEntity) { $existingOid = spl_object_hash($existingEntity); if (isset($this->cachedEntities[$existingOid])) { return $existingEntity; } $this->cachedEntities[$existingOid] = $existingEntity; } else { // if can't find entity and new entity can't be persisted if (!$isPersistNew) { return null; } $this->databaseHelper->resetIdentifier($entity); $this->cachedEntities[$oid] = $entity; } // update relations if ($isFullData) { $this->updateRelations($entity, $itemData); } // import entity fields if ($existingEntity) { if ($isFullData) { $this->importExistingEntity($entity, $existingEntity, $itemData); } $entity = $existingEntity; } return $entity; }
/** * @param object $entity * @param string $field * @param string $locale * @param mixed $fieldData * @throws \Bigfoot\Bundle\CoreBundle\Exception\InvalidArgumentException */ public function translate($entity, $field, $locale, $fieldData) { $em = $this->em; $meta = $em->getClassMetadata(get_class($entity)); $listener = $this->getTranslatableListener(); $persistDefaultLocaleTransInEntity = $listener->getPersistDefaultLocaleTranslation(); if (is_object($entity)) { $entityClass = $entity instanceof Proxy ? get_parent_class($entity) : get_class($entity); } else { throw new InvalidArgumentException('Argument 1 passed to TranslationRepository::translate must be an object'); } $reflectionClass = new \ReflectionClass($entityClass); $entityTranslationClass = $this->isPersonnalTranslationRecursive($reflectionClass)->class; if ($locale === $listener->getTranslatableLocale($entity, $meta)) { $meta->getReflectionProperty($field)->setValue($entity, $fieldData); $em->persist($entity); } elseif (!$persistDefaultLocaleTransInEntity && $locale === $listener->getDefaultLocale()) { $trans = new $entityTranslationClass($locale, $field, $fieldData); $listener->setTranslationInDefaultLocale(spl_object_hash($entity), $field, $trans); } else { $translationClassRepository = $this->em->getRepository($entityTranslationClass); $meta = $em->getClassMetadata(get_class($entity)); $identifier = $meta->getSingleIdentifierFieldName(); $translation = null; if ($entity && $this->propertyAccessor->getValue($entity, $identifier)) { $translation = $translationClassRepository->findOneBy(array('locale' => $locale, 'field' => $field, 'object' => $entity)); } if ($translation) { $translation->setContent($fieldData); } elseif ($fieldData !== null) { $entity->addTranslation(new $entityTranslationClass($locale, $field, $fieldData)); } } }
/** * @param \PHPUnit_Framework_TestResult $result */ public function printResult(\PHPUnit_Framework_TestResult $result) { if ($this->runner->shouldNotify()) { ob_start(); } $testDox = trim(TestDox::get(spl_object_hash($result))); if (strlen($testDox)) { $this->write(PHP_EOL . PHP_EOL . $testDox); } parent::printResult($result); if ($this->runner->shouldNotify()) { $output = ob_get_contents(); ob_end_clean(); echo $output; if ($result->failureCount() + $result->errorCount() + $result->skippedCount() + $result->notImplementedCount() == 0) { $notificationResult = Notification::RESULT_PASSED; } else { $notificationResult = Notification::RESULT_FAILED; } $output = $this->removeAnsiEscapeCodesForColors($output); if (preg_match('/(OK \\(\\d+ tests?, \\d+ assertions?\\))/', $output, $matches)) { $notificationMessage = $matches[1]; } elseif (preg_match('/(FAILURES!)\\s+(.*)/', $output, $matches)) { $notificationMessage = $matches[1] . PHP_EOL . $matches[2]; } elseif (preg_match('/(OK, but incomplete,.*!)\\s+(.*)/', $output, $matches)) { $notificationMessage = $matches[1] . PHP_EOL . $matches[2]; } elseif (preg_match('/(No tests executed!)/', $output, $matches)) { $notificationMessage = $matches[1]; } else { $notificationMessage = ''; } $this->notification = new Notification($notificationResult, $notificationMessage); } }
/** * @param Request $request * * @return Response */ public function __invoke(Request $request) { $options = []; // Headers $headerLines = []; foreach ($request->getHeaders() as $name => $values) { $headerLines[] = sprintf('%s: %s', $name, implode(', ', $values)); } $options[CURLOPT_HTTPHEADER] = $headerLines; // Url $options[CURLOPT_URL] = (string) $request->getUri(); switch ($request->getMethod()) { case 'HEAD': $options[CURLOPT_NOBODY] = true; break; case 'GET': $options[CURLOPT_HTTPGET] = true; break; case 'POST': $options[CURLOPT_POST] = true; $options[CURLOPT_POSTFIELDS] = (string) $request->getBody(); // Don't duplicate the Content-Length header $request = $request->withoutHeader('Content-Length'); $request = $request->withoutHeader('Transfer-Encoding'); break; case 'PUT': // Write to memory/temp $file = fopen('php://temp/' . spl_object_hash($request), 'w+'); $bytes = fwrite($file, (string) $request->getBody()); rewind($file); $options[CURLOPT_PUT] = true; $options[CURLOPT_INFILE] = $file; $options[CURLOPT_INFILESIZE] = $bytes; $request = $request->withoutHeader('Content-Length'); break; default: $options[CURLOPT_CUSTOMREQUEST] = $request->getMethod(); } // If the Expect header is not present, prevent curl from adding it if (!$request->hasHeader('Expect')) { $options[CURLOPT_HTTPHEADER][] = 'Expect:'; } // cURL sometimes adds a content-type by default. Prevent this. if (!$request->hasHeader('Content-Type')) { $options[CURLOPT_HTTPHEADER][] = 'Content-Type:'; } list($body, $headerLines) = $this->execute($options); $headerLines = preg_split("#\r\n#", $headerLines, -1, PREG_SPLIT_NO_EMPTY); $headers = []; // Extract the version and status from the first header preg_match('#HTTP/(\\d\\.\\d)\\s(\\d\\d\\d)\\s(.*)#', array_shift($headerLines), $matches); array_shift($matches); list($protocolVersion, $statusCode, $reasonPhrase) = $matches; foreach ($headerLines as $line) { list($name, $values) = preg_split('#\\s*:\\s*#', $line, 2, PREG_SPLIT_NO_EMPTY); $headers[$name] = preg_split('#\\s*,\\s*#', $values, -1, PREG_SPLIT_NO_EMPTY); } $response = new \GuzzleHttp\Psr7\Response($statusCode, $headers, $body, $protocolVersion, $reasonPhrase); return $response; }