Пример #1
0
 /**
  *
  */
 public function install_application()
 {
     foreach (new \DirectoryIterator(APP_DIR . 'model') as $fi) {
         if ($fi->isDot()) {
             continue;
         }
         if ($fi->getExtension() != 'php') {
             continue;
         }
         $filename = $fi->getFilename();
         $class = ns(substr($filename, 0, -4));
         $trait = ns('ModelTrait');
         if (!self::load('model/' . $filename)) {
             trigger_error("Model file ({$filename}) could not be loaded", E_USER_ERROR);
         }
         if (!class_exists($class)) {
             trigger_error("Model file ({$filename}) found without defining class \"{$class}\"", E_USER_ERROR);
         }
         if (!in_array($trait, class_uses($class))) {
             trigger_error("Model class ({$class}) does not use required trait \"{$trait}\"", E_USER_ERROR);
         }
         echo "Integrating schema for model: {$class}\n";
         $class::integrate_schema();
     }
     die("-- Installation complete --\n");
 }
 /**
  * It should use Eloquence\Behaviours\Uuid;
  *
  * @test
  * @return void
  */
 public function it_should_use_EloquenceBehavioursUuid()
 {
     $traitList = class_uses($this->uuidModelWithValidation);
     $this->assertArrayHasKey("Eloquence\\Behaviours\\Uuid", $traitList);
     $this->assertClassHasAttribute('incrementing', 'Elozoya\\LaravelCommon\\UuidModelWithValidation');
     $this->assertFalse($this->uuidModelWithValidation->incrementing);
 }
Пример #3
0
 /**
  * Return a simple list of entries in the table.
  *
  * May cache the results for up to 60 minutes.
  *
  * @return	array of Fluent objects
  */
 public static function tableToArray()
 {
     $me = new static();
     $cache_key = $me->cacheKey();
     // Return the array from the cache if it is present.
     if (Cache::has($cache_key)) {
         return (array) Cache::get($cache_key);
     }
     // Otherwise put the results into the cache and return them.
     $results = [];
     $query = static::all();
     // If the current model uses softDeletes then fix the
     // query to exclude those objects.
     foreach (class_uses(__CLASS__) as $traitName) {
         if ($traitName == 'SoftDeletes') {
             $query = static::whereNull('deleted_at')->get();
             break;
         }
     }
     /** @var Cacheable $row */
     foreach ($query as $row) {
         $results[$row->getIndexKey()] = $row->toFluent();
     }
     Cache::put($cache_key, $results, 60);
     return $results;
 }
Пример #4
0
 /**
  * Checks the object uses the correct trait, and
  * implements the correct interface.
  *
  * @author Daniel Sherman
  * @test
  */
 public function testTraitAndInterface()
 {
     $msg = 'the object does not implement the correct interface';
     $this->assertInstanceOf('Flair\\Configuration\\SetsInterface', self::$obj, $msg);
     $msg = 'the object does not use the correct trait';
     $this->assertContains('Flair\\Configuration\\SetsTrait', class_uses(self::$obj), $msg);
 }
Пример #5
0
 /**
  * {@inheritdoc}
  */
 protected function findExistingEntity($entity, array $searchContext = [])
 {
     $entityName = ClassUtils::getClass($entity);
     $identifier = $this->databaseHelper->getIdentifier($entity);
     $existingEntity = null;
     // find by identifier
     if ($identifier) {
         $existingEntity = $this->databaseHelper->find($entityName, $identifier);
     }
     // find by identity fields
     if (!$existingEntity && (!$searchContext || $this->databaseHelper->getIdentifier(current($searchContext)))) {
         $identityValues = $searchContext;
         $usedTraits = class_uses($entityName);
         if ($this->context->hasOption('channel') && in_array(self::TARGET_TRAIT, $usedTraits)) {
             $channel = $this->databaseHelper->findOneBy('Oro\\Bundle\\IntegrationBundle\\Entity\\Channel', ['id' => $this->context->getOption('channel')]);
             $identityValues['channel'] = $channel;
         }
         $identityValues += $this->fieldHelper->getIdentityValues($entity);
         $existingEntity = $this->findEntityByIdentityValues($entityName, $identityValues);
     }
     if ($existingEntity && !$identifier) {
         $identifier = $this->databaseHelper->getIdentifier($existingEntity);
         $identifierName = $this->databaseHelper->getIdentifierFieldName($entity);
         $this->fieldHelper->setObjectValue($entity, $identifierName, $identifier);
     }
     return $existingEntity;
 }
 /**
  * Check if $object is translatable.
  *
  * @param mixed $object
  *
  * @return bool
  */
 public function isTranslatable($object)
 {
     if ($object === null) {
         return false;
     }
     if (function_exists('class_uses')) {
         $traits = class_uses($object);
         if (in_array('Sonata\\TranslationBundle\\Traits\\Translatable', $traits)) {
             return true;
         }
         if (in_array('Sonata\\TranslationBundle\\Traits\\Gedmo\\PersonalTranslatable', $traits)) {
             return true;
         }
     }
     $objectInterfaces = class_implements($object);
     foreach ($this->getSupportedInterfaces() as $interface) {
         if (in_array($interface, $objectInterfaces)) {
             return true;
         }
     }
     foreach ($this->getSupportedModels() as $model) {
         if ($object instanceof $model) {
             return true;
         }
     }
     return false;
 }
 private function formatValue($value)
 {
     if (is_scalar($value)) {
         return $value;
         // If the object uses this trait
     } elseif (is_a($value, 'Doctrine\\ODM\\MongoDB\\PersistentCollection')) {
         $prop = [];
         foreach ($value as $k => $v) {
             $prop[$k] = $this->formatValue($v);
         }
         return $prop;
         // If it's a Date, convert to unix timestamp
     } elseif (is_a($value, 'Date')) {
         return $value->getTimestamp();
         // Otherwise leave a note that this type is not formatted
         // So that I can add formatting for this missed class
     } elseif (is_array($value)) {
         return $value;
     } elseif (in_array(__TRAIT__, class_uses(get_class($value))) && method_exists($value, 'toStdClass')) {
         return $value->toStdClass();
         // If it's a collection, format each value
     } else {
         return 'Not formatted in DocumentSerializer: ' . get_class($value);
     }
 }
Пример #8
0
 /**
  * Get action delete for translation name
  * @return string Name
  */
 public function actionForStringDelete()
 {
     if (in_array('Illuminate\\Database\\Eloquent\\SoftDeletes', class_uses($this->entity))) {
         return 'archive';
     }
     return 'delete';
 }
Пример #9
0
 public function __construct($route, $app)
 {
     $this->app = $app;
     $this->route = $route;
     static::$instance = $this;
     //init use trait
     foreach (class_uses($this) as $_trait) {
         $_method = str_replace('\\', '_', $_trait);
         if (method_exists($this, $_method)) {
             $this->{$_method}();
         }
     }
     //load from app
     if (is_null($this->response)) {
         $this->response = $this->app->response;
     }
     if (is_null($this->request)) {
         $this->request = $this->app->request;
     }
     //run
     $r = $this->exec($this->route[1], true, true);
     //back to app
     $this->app->response = $this->response;
     return $r;
 }
Пример #10
0
 /**
  * 
  * @param mixed $class
  * @param string $trait
  * @param boolean $recursive
  * @return boolean
  */
 public static function classUses($class, $trait, $recursive = true)
 {
     if (!\is_object($class) && !\is_string($class)) {
         return false;
     }
     $traits = \class_uses($class);
     if ($recursive) {
         $parent = \get_parent_class($class);
         while ($parent !== false) {
             $traits = \array_merge($traits, \class_uses($parent));
             $parent = \get_parent_class($parent);
         }
     }
     if (!is_array($trait)) {
         $trait = (array) $trait;
     }
     foreach ($traits as $k => $t) {
         if (\in_array($t, $trait)) {
             return true;
         }
         if (self::classUses($t, $trait)) {
             return true;
         }
         unset($traits[$k]);
     }
     return false;
 }
Пример #11
0
 /**
  * @Route("eliminar2/")
  * @Template("TapirBaseBundle:Default:eliminar2.html.twig")
  * @Sensio\Bundle\FrameworkExtraBundle\Configuration\Method("POST")
  */
 public function eliminar2Action(Request $request)
 {
     $id = $this->ObtenerVariable($request, 'id');
     $form = $this->CrearFormEliminar($id);
     $form->handleRequest($request);
     if ($form->isValid()) {
         $em = $this->getEm();
         $entity = $em->getRepository($this->VendorName . $this->BundleName . 'Bundle:' . $this->EntityName)->find($id);
         if (in_array('Tapir\\BaseBundle\\Entity\\Suprimible', class_uses($entity))) {
             // Es suprimible (soft-deletable), lo marco como borrado, pero no lo borro
             $entity->Suprimir();
             $em->persist($entity);
             $em->flush();
             $this->get('session')->getFlashBag()->add('info', 'Se suprimió el elemento "' . $entity . '".');
             return $this->afterEliminar($request, $entity, true);
         } else {
             if (in_array('Tapir\\BaseBundle\\Entity\\Eliminable', class_uses($entity))) {
                 // Es eliminable... lo elimino de verdad
                 $em->remove($entity);
                 $em->flush();
                 $this->get('session')->getFlashBag()->add('info', 'Se eliminó el elemento "' . $entity . '".');
                 return $this->afterEliminar($request, $entity, true);
             } else {
                 // No es eliminable ni suprimible... no se puede borrar
                 $this->get('session')->getFlashBag()->add('info', 'No se puede eliminar el elemento "' . $entity . '".');
             }
         }
     }
     return $this->afterEliminar($request, $entity);
 }
Пример #12
0
 /**
  * Checks the object uses the correct trait, and
  * implements the correct interface.
  *
  * @author Daniel Sherman
  * @test
  * @covers ::__construct
  */
 public function testConstruct()
 {
     $msg = 'the object does not implement the correct interface';
     $this->assertInstanceOf('Flair\\Validation\\RuleMessageInterface', self::$obj, $msg);
     $msg = 'the object does not use the correct trait';
     $this->assertContains('Flair\\Validation\\RuleMessageTrait', class_uses(self::$obj), $msg);
 }
Пример #13
0
 /**
  * Test that the Model uses the traits and in the right order.
  */
 public function testModelUsesTraits()
 {
     // Get the traits off the model
     $traits = function_exists('class_uses_recursive') ? class_uses_recursive(get_class($this->model)) : class_uses(get_class($this->model));
     // Check Model uses the Soft Deleting trait
     $this->assertContains('Esensi\\Model\\Traits\\SoftDeletingModelTrait', $traits);
 }
 /**
  * Register the custom router macro.
  */
 protected function registerRouterMacro()
 {
     $this->app['router']->macro('fakeIdModel', function ($key, $class, Closure $callback = null) {
         $this->bind($key, function ($value) use($key, $class, $callback) {
             if (is_null($value)) {
                 return;
             }
             // For model binders, we will attempt to retrieve the models using the first
             // method on the model instance. If we cannot retrieve the models we'll
             // throw a not found exception otherwise we will return the instance.
             $instance = $this->container->make($class);
             // Decode FakeId first if applicable.
             if (in_array('Propaganistas\\LaravelFakeId\\FakeIdTrait', class_uses($class))) {
                 $value = $this->container->make('fakeid')->decode($value);
             }
             if ($model = $instance->where($instance->getRouteKeyName(), $value)->first()) {
                 return $model;
             }
             // If a callback was supplied to the method we will call that to determine
             // what we should do when the model is not found. This just gives these
             // developer a little greater flexibility to decide what will happen.
             if ($callback instanceof Closure) {
                 return call_user_func($callback, $value);
             }
             throw new NotFoundHttpException();
         });
     });
 }
 /**
  * Returns attributes for the resource
  *
  * @return mixed[]
  */
 public function getResourceAttributes()
 {
     $attributes = $this->attributesToArray();
     // detect any translated attributes
     if (in_array(config('jsonapi.encoding.translatable_trait'), class_uses($this))) {
         foreach ($this->translatedAttributes as $key) {
             $attributes[$key] = $this->{$key};
         }
     }
     // unset primary key field
     unset($attributes[$this->getKeyName()]);
     // unset reserved fieldname "type"
     // reset it as modelname-type if that is not in use yet
     if (array_key_exists('type', $attributes)) {
         $typeRecast = Str::snake(class_basename($this) . '-type', '-');
         if (!array_key_exists($typeRecast, $attributes)) {
             $attributes[$typeRecast] = $attributes['type'];
         }
         unset($attributes['type']);
     }
     // map all fieldnames to dasherized case
     foreach ($attributes as $key => $value) {
         $dasherized = str_replace('_', '-', $key);
         if ($key !== $dasherized) {
             $attributes[$dasherized] = $value;
             unset($attributes[$key]);
         }
     }
     return $attributes;
 }
Пример #16
0
 public static function findSearchableModels($directories)
 {
     $models = [];
     // Iterate over each directory and inspect files for models
     foreach ($directories as $directory) {
         $dir = new DirectoryIterator($directory);
         foreach ($dir as $fileinfo) {
             $namespace = '';
             if (!$fileinfo->isDot() && $fileinfo->isReadable()) {
                 $fileObj = $fileinfo->openFile('r');
                 while (!$fileObj->eof()) {
                     $line = $fileObj->fgets();
                     // Extract namespace
                     if (preg_match('/namespace\\s+([a-zA-z0-9]+)/', $line, $matches)) {
                         $namespace = $matches[1];
                     }
                     // Extract classname
                     if (preg_match('/class\\s+([a-zA-z0-9]+)/', $line, $matches)) {
                         $model = $namespace ? $namespace . '\\' . $matches[1] : $matches[1];
                         // Check if the model has the searchable trait
                         if (in_array('Iverberk\\Larasearch\\Traits\\SearchableTrait', class_uses($model))) {
                             $models[] = $model;
                         }
                     }
                 }
             }
         }
     }
     return $models;
 }
Пример #17
0
 /**
  * @param array $fieldNames
  *
  * @throws ResourceException when there's no data to save
  * @return $this
  */
 public function save(array $fieldNames = [])
 {
     if ([] === $fieldNames) {
         $fieldNames = array_keys($this->data);
         if ([] === $fieldNames) {
             //@codeCoverageIgnoreStart
             throw new ResourceException('No data to save');
             //@codeCoverageIgnoreEnd
         }
         return $this->save($fieldNames);
     }
     $resourceName = $this->getResourceName();
     $uri = $this->getFullUri();
     $data = $this->dehydrate($fieldNames);
     if (in_array(CustomFieldsTrait::class, class_uses($this))) {
         /** @noinspection PhpUndefinedMethodInspection */
         $customFields = $this->getCustomFields()->toArray();
         if ([] !== $customFields) {
             $data[CustomFields::KEY_SAVING] = $customFields;
         }
     }
     $response = $this->transport->put($uri, $resourceName, ['query' => [$resourceName => $data]]);
     $this->hydrate($response);
     return $this;
 }
Пример #18
0
/**
 * Retrieve information about a class.
 * 
 * Much like pathinfo(), it will return only information that 
 * is available, unless a particular item(s) is specified.
 * 
 * Returns, if available, as part of the array:
 * 	1. 'vendor' (string) the top-level namespace name.
 *  2. 'namespaces' (array) the "middle" namespaces, 0-indexed.
 *  3. 'class' (string) the base classname, always available.
 * 
 * @param string|object $class Classname or object to get info on.
 * @param int $flag Bitwise INFO_* flags. Default INFO_BASIC.
 * @return string|array String if flag given and found, otherwise array of info.
 */
function class_info($class, $flag = INFO_BASIC)
{
    $info = array();
    if (!is_string($class)) {
        $class = get_class($class);
    } else {
        $class = trim($class, '\\');
    }
    if (false === strpos($class, '\\')) {
        if ($flag === INFO_CLASSNAME) {
            return $class;
        }
        $info['class'] = $class;
        if (!INFO_INTERFACES & $flag && !INFO_PARENTS & $flag) {
            return $info;
        }
    }
    $parts = explode('\\', $class);
    $num = count($parts);
    if ($flag === INFO_CLASSNAME) {
        return $parts[$num - 1];
    }
    if ($flag === INFO_VENDOR) {
        return $parts[0];
    }
    if ($flag & INFO_VENDOR) {
        $info['vendor'] = $parts[0];
    }
    if ($num > 2 && $flag & INFO_NAMESPACES) {
        $info['namespaces'] = array();
        for ($i = 1; $i < $num - 1; $i++) {
            $info['namespaces'][] = $parts[$i];
        }
    }
    if ($flag === INFO_NAMESPACES) {
        return isset($info['namespaces']) ? $info['namespaces'] : null;
    }
    if ($flag & INFO_CLASSNAME) {
        $info['class'] = $parts[$num - 1];
    }
    if ($flag & INFO_PARENTS) {
        $info['parents'] = array_values(class_parents($class));
        if ($flag === INFO_PARENTS) {
            return $info['parents'];
        }
    }
    if ($flag & INFO_INTERFACES) {
        $info['interfaces'] = array_values(class_implements($class));
        if ($flag === INFO_INTERFACES) {
            return $info['interfaces'];
        }
    }
    if ($flag & INFO_TRAITS) {
        $info['traits'] = array_values(class_uses($class));
        if ($flag === INFO_TRAITS) {
            return $info['traits'];
        }
    }
    return $info;
}
Пример #19
0
 public function display_form_table_inputs($o)
 {
     if ($o->header != '') {
         $o->r .= sprintf('<%s class="title">%s</%s>%s', $o->header_level, $o->header, $o->header_level, "\n");
     }
     $o->table = $this->base->table()->set_attribute('class', 'form-table');
     foreach ($o->inputs as $input) {
         // Input containers (fieldsets) must be recursed.
         $container = false;
         $container |= is_subclass_of($input, 'plainview\\sdk_broadcast\\form2\\inputs\\inputfieldset');
         $uses = class_uses($input);
         $container |= isset($uses['plainview\\sdk_broadcast\\form2\\inputs\\traits\\container']);
         if ($container) {
             // Should the table be displayed?
             if (count($o->table->body->rows) > 0) {
                 $o->r .= $o->table;
             }
             // Clone the options object to allow the input container to create its own table
             $o2 = clone $o;
             $o2->header = $input->label;
             // If this is a container with a legend (fieldset) use the legend.
             if (isset($input->legend)) {
                 $o2->header = $input->legend->label->content;
             }
             $o2->inputs = $input->inputs;
             $o2->r = '';
             $o2->table = $this->base->table()->set_attribute('class', 'form-table');
             $this->display_form_table_inputs($o2);
             $o->table = $this->base->table()->set_attribute('class', 'form-table');
             $o->r .= sprintf('<div class="fieldset fieldset_%s">%s</div>', $input->get_name(), $o2->r);
             continue;
         }
         // Hidden inputs cannot be displayed.
         if ($input->get_attribute('hidden')) {
             $o->r .= $input->display_input();
             continue;
         }
         if (is_a($input, 'plainview\\sdk_broadcast\\form2\\inputs\\markup')) {
             $o->table->body()->row()->td()->set_attribute('colspan', 2)->text($input->display_input());
             continue;
         }
         $description = $input->display_description($input);
         if ($description != '') {
             $description = sprintf('<div class="input_description">%s</div>', $description);
         }
         $row = $o->table->body()->row();
         if (!$input->validates()) {
             $row->css_class('does_not_validate');
         }
         $label = $input->display_label();
         if ($input->is_required()) {
             $label .= sprintf(' <sup><abbr title="">*</abbr></sup>', $this->base->_('This input is required.'));
         }
         $row->th()->text($label)->row()->td()->textf('<div class="input_itself">%s</div>%s', $input->display_input($input), $description);
     }
     if (count($o->table->body->rows) > 0) {
         $o->r .= $o->table;
     }
 }
Пример #20
0
 /**
  * {@inheritDoc}
  */
 public function delete()
 {
     $isSoftDeleted = array_key_exists('Illuminate\\Database\\Eloquent\\SoftDeletes', class_uses($this));
     if ($this->exists && !$isSoftDeleted) {
         $this->users()->detach();
     }
     return parent::delete();
 }
Пример #21
0
 private function collectTraits($class, array &$all_traits = [])
 {
     $traits = class_uses($class);
     foreach ($traits as $trait) {
         $this->collectTraits($trait, $traits);
     }
     $all_traits += $traits;
 }
 /**
  * @param $className
  *
  * @return array
  */
 private static function getClassTraits($className)
 {
     $traits = class_uses($className);
     while ($className = get_parent_class($className)) {
         $traits += class_uses($className);
     }
     return $traits;
 }
Пример #23
0
 public function testUsesSoftDeletingTrait()
 {
     $traits = class_uses($this->model);
     foreach (class_parents($this->model) as $parent) {
         $traits += class_uses($parent);
     }
     $this->assertContains('Illuminate\\Database\\Eloquent\\SoftDeletes', $traits);
 }
Пример #24
0
 /**
  * Returns all traits used by a trait and its traits.
  *
  * @param  string $trait
  * @return array
  */
 public static function traitUsesRecursive($trait)
 {
     $traits = class_uses($trait);
     foreach ($traits as $trait) {
         $traits += static::traitUsesRecursive($trait);
     }
     return $traits;
 }
Пример #25
0
 /**
  * User relation for the activity
  *
  * @return User
  */
 public function user()
 {
     $relation = $this->belongsTo($this->getUserModelName());
     if (in_array('Illuminate\\Database\\Eloquent\\SoftDeletes', class_uses($this->getUserModelName()))) {
         $relation->withTrashed();
     }
     return $relation;
 }
Пример #26
0
 /**
  * Only trashed.
  */
 public function onlyTrashed()
 {
     if (!in_array(SoftDeletes::class, class_uses($this->model))) {
         throw new RepositoryException("Class {$this->model()} must be an instance of Illuminate\\Database\\Eloquent\\SoftDeletes");
     }
     $this->model = $this->makeModel()->onlyTrashed();
     return $this;
 }
Пример #27
0
 /**
  * Return an array of all the Traits that a given
  * $class and it's parents use.
  *
  * @param $class
  * @param bool $autoload
  * @return array
  */
 public static function getTraits($class, $autoload = true)
 {
     $traits = array();
     do {
         $traits = array_merge(class_uses($class, $autoload), $traits);
     } while ($class = get_parent_class($class));
     return array_unique($traits);
 }
Пример #28
0
 /**
  * Checks that the:
  *
  *   - Semver task is used
  *
  * @return boolean
  */
 protected function bumperSemVerReady()
 {
     $task = 'Robot\\Task\\SemVer';
     if (!in_array($task, class_uses($this))) {
         throw new RequiredTaskException('Bumper', $task);
     }
     return true;
 }
Пример #29
0
 /**
  * @return bool
  */
 public function isActivated()
 {
     $result = !empty($this->activated_at);
     if (array_key_exists('cookyii\\db\\traits\\SoftDeleteTrait', class_uses($this))) {
         $result = $result && !$this->isDeleted();
     }
     return $result;
 }
 public function serialize($object)
 {
     if (!in_array(SimpleEntityTrait::class, class_uses($object))) {
         throw new UnsupportedObjectException($object, 'Can only serialize instances of SimpleEntityTrait');
     }
     $this->entity = $object;
     return $this->serializeEntity();
 }